Change ViewPager Fragment From Child Fragment

后端 未结 2 1461
攒了一身酷
攒了一身酷 2021-01-12 18:06

I have a ViewPager using a TabLayout with several fragments. I would like to click a button from one of the ViewPager fragments and direct the user to another tab/fragment u

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 18:42

    the easiest way to achieve this, using an EventBus framework!

    I prefer(ed) using EventBus by greenRobot

    How to implement:

    1) Create an event class which fulfills your needs

    public class ClickedButtonInsideFragmentEvent {
    
        // some data you want to store
    
    }
    

    2) prepare your subscribers! In your case this would be the Activity which holds the reference to the tab layout:

    public class MyTabActivity {
    
        public void onCreate(Bundle savedInstanceSate) {
            // your stuff you do in onCreate
            eventBus.register(this);
        }
    
        @Subscribe  
        public void onEvent(ClickedButtonInsideFragmentEvent event) {
            // Do what you want to do
        } 
    
    }
    

    3) and finally: post the event from your OnClickListener insider your fragment:

    public class MyClickableFragment {
    
        public void initOnClickListiner(View clickableView) {
            clickableView.setOnClickListener(new OnClickListener() {
                public void onClick(View view) {
                    ClickedButtonInsideFragmentEvent event = new ClickedButtonInsideFragmentEvent();
                    // add what you want to your event
                    eventBus.post(event);                
                }
            ));
        }
    
        @Subscribe  
        public void onEvent(ClickedButtonInsideFragmentEvent event) {
            // Do what you want to do
        } 
    
    }
    

提交回复
热议问题