每当片段在viewpager中可见时,如何创建仪表动画?

时间:2019-06-05 19:48:31

标签: android android-viewpager gauge

我能够找到问题的解决方案“如何检查片段是否在viewpager中可见”。但是,我也希望每当片段出现在屏幕上时,我的量规就进行动画处理。但是,它返回空指针异常。我使用过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();

        }
    }

1 个答案:

答案 0 :(得分:0)

您没有初始化变量,只是为变量提供默认值

public Boolean mIsVisibleToUser = false;