Change ViewPager Fragment From Child Fragment

心已入冬 提交于 2019-12-05 11:28:16

You should write a method in the parent (containing the ViewPager and the sub-fragments) like so:

public void setPagerFragment(int a)
{
    pager.setCurrentItem(a);
}

This will set the current Fragment in the ViewPager to be the one specified. You can then call this method from the child Fragment with:

int newFrag = 0; //the number of the new Fragment to show
ParentActivity parent = (ParentActivity) getActivity();
parent.setPagerFragment(newFrag);

Regarding sending additional data with the request to show on the new fragment, you can make another method in the parent, to be called in the child, which will set some data in the parent, which the parent can then use when setting the new fragment.

For example in the parent:

public void setExtraData(Object data)
{
    dataFromChildFrag = data;
}

And use this in the child like so:

String data = "My extra data"; //the number of the new Fragment to show
ParentActivity parent = (ParentActivity) getActivity();
parent.setExtraData(data);

Finally, if the parent is in fact a Fragment itself rather than an Activity, simply replace all references of:

ParentActivity parent = (ParentActivity) getActivity();

to:

ParentFragment parent = (ParentFragment) getParentFragment();

I hope this helps!

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
    } 

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!