Update ViewPager dynamically?

后端 未结 20 3062
时光说笑
时光说笑 2020-11-22 02:00

I can\'t update the content in ViewPager.

What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?

I was using onl

20条回答
  •  灰色年华
    2020-11-22 02:33

    I use EventBus library to update Fragment content in ViewPager. The logic is simple, just like document of EventBus how to do. It is no need to control FragmentPagerAdapter instance. The code is here:

    1: Define events

    Define which message which is needed to update.

    public class UpdateCountEvent {
        public final int count;
    
        public UpdateCountEvent(int count) {
            this.count = count;
        }
    }
    

    2.Prepare subscribers

    Write below code in the Fragment which is needed update.

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);  
        super.onStop();
    }
    
    public void onEvent(UpdateCountEvent event) {//get update message
        Toast.makeText(getActivity(), event.count, Toast.LENGTH_SHORT).show();
    }
    

    3.Post events

    Write below code in other Activity or other Fragment which needs to update parameter

    //input update message
    EventBus.getDefault().post(new UpdateCountEvent(count));
    

提交回复
热议问题