从子片段更改ViewPager片段 [英] Change ViewPager Fragment From Child Fragment

查看:81
本文介绍了从子片段更改ViewPager片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用TabLayout的ViewPager,其中包含几个片段.我想单击一个ViewPager片段中的一个按钮,然后使用选项卡名称将用户定向到另一个选项卡/片段.

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 using the tab name.

单击按钮时,我希望更改TabLayout并显示与该选项卡关联的片段.我还需要发送带有请求的其他数据,以显示在新片段上.

When the button is clicked, I would like the TabLayout to change as well as show the fragment associated to that tab. I would also need to send additional data with the request to show on the new fragment.

我无权访问ViewPager setCurrentItem(int index).理想情况下,我想与父母沟通以完成请求.

I don't have access to the ViewPager setCurrentItem(int index). Ideally I would like to communicate with the parent to complete the request.

推荐答案

您应该像这样在父级(包含ViewPager和子片段)中编写一个方法:

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);
}

这会将ViewPager中的当前片段设置为指定的片段.然后,您可以使用以下子项从子Fragment调用此方法:

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.

例如在父母中:

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);

最后,如果父级实际上是Fragment本身而不是Activity,则只需替换以下所有引用:

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

ParentActivity parent = (ParentActivity) getActivity();

收件人:

ParentFragment parent = (ParentFragment) getParentFragment();

我希望这会有所帮助!

这篇关于从子片段更改ViewPager片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆