Want to start animation on viewpager page but pages are preloading

前端 未结 2 488
天命终不由人
天命终不由人 2021-01-21 21:58

In my projects I have several screen(Fragments) and I want to give animation to the fragments elements(views). I have used view pager and viewpager adapter and fragments. The ma

2条回答
  •  攒了一身酷
    2021-01-21 22:29

    Overriding setUserVisibleHint() in each of my pages/fragments worked for me. You can simply call view.startAnimation(animation) inside your setUserVisibleHint(). However, there is one problem with this approach:

    In fragments, setUserVisibleHint() gets called before onCreateView() and onViewCreated.

    The implication of this is that when the fragment starts for the first time and you call view.startAnimation(animation) inside setUserVisibleHint(), view and animation would both be null and the app would crash.


    How then can you fix this problem?

    In each of your pages/fragments, simply declare a global boolean (let's call it fresh_load), use this boolean to check whether the fragment is being loaded for the first time. Here's an illustration:

    boolean fresh_load = true;
    Animation move;
    ImageView car;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_carousel_two, container, false);
    
        // init move and car variables
    
        if(fresh_load) {
            car.startAnimation(animation);
            fresh_load = false;
        }
    
        return view;
    }
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    
        if((isVisible() && animation != null) && !fresh_load) {
            car.startAnimation(move);
        }
    }
    

    I hope this helps. Merry coding!

提交回复
热议问题