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

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

问题描述

我有一个 ViewPager,它使用带有多个片段的 TabLayout.我想从其中一个 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天全站免登陆