每次片段在 viewpager 中可见时,如何创建 Gauge 动画?

How can I create Gauge animation everytime a fragment becomes visible in viewpager?

我找到了问题的解决方案 "how to check if a fragment becomes visible in viewpager"。但是,我还希望每次片段出现在屏幕上时,我的仪表都能显示动画。但是,它returns 空指针异常。我使用了 isVisibleToUser 方法和 onResume() 方法。我该如何解决?

public class HumidityFragment extends Fragment {
    View view;

    public Boolean mIsVisibleToUser;

    Gauge gauge;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_soil_moisture, container, false);

            gauge = view.findViewById(R.id.gauge);
            onVisible();



        return view;
    }
        @Override
        public void onStart () {
            super.onStart();
            if (mIsVisibleToUser) {
                onVisible();
            }
        }

    @Override
    public void onResume() {
        super.onResume();
        onVisible();
    }

    @Override
        public void onStop () {
            super.onStop();
            if (mIsVisibleToUser) {
                onInVisible();
            }
        }


        @Override
        public void setUserVisibleHint ( boolean isVisibleToUser){
            super.setUserVisibleHint(isVisibleToUser);
            mIsVisibleToUser = isVisibleToUser;
            if (isResumed()) { // fragment have created
                if (mIsVisibleToUser) {
                    onVisible();
                } else {
                    onInVisible();
                }
            }
        }

        public void onVisible () {
            Toast.makeText(getContext(), "visible", Toast.LENGTH_SHORT).show();

                gauge.moveToValue(78);


        }

        public void onInVisible () {
            Toast.makeText(getActivity(), "invisible", Toast.LENGTH_SHORT).show();

        }
    }

你没有初始化变量只是给你的变量赋了默认值

public Boolean mIsVisibleToUser = false;