在Tabs android中添加片段的最佳方法是什么? [英] What is the best way to add fragment in the Tabs android

查看:119
本文介绍了在Tabs android中添加片段的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一个底部导航栏,有5个标签。
所以根据这些标签,我有5个片段
当我点击标签时,片段根据该标签更改。
我可以使用beginTransaction()方法切换片段。替换...
我不希望每次切换标签时都会破坏并重新创建片段,所以我的解决方案就像这样

My application had a bottom navigation bar which has 5 tabs. So according to these tabs, I have 5 fragments When I click on the tab, the fragment changed according to that tab. I can switch fragment by using the method beginTransaction().replace... I dont want the fragment to be destroyed and recreated again each time I switch tabs, so my solution is sth like this

//I init 5 fragments
Fragment1 frag1 = new Fragment1();
Fragment2 frag2 = new Fragment2();
Fragment3 frag3 = new Fragment3();
Fragment4 frag4 = new Fragment4();
Fragment5 frag5 = new Fragment5();

//When I click on tab, for example tab1, I hide all fragments except tab1
//hide all fragments
getSupportFragmentManager()
                    .beginTransaction()
                    .hide(fragment1) //Fragment2, 3, 4, 5 as well
                    .commit();

//show fragment 1
getSupportFragmentManager()
                    .beginTransaction()
                    .show(fragment1)
                    .commit();

它的效果非常好,但问题是有时会同时显示2个片段(我不知道为什么因为我隐藏了所有碎片)
任何其他方法来实现这一目标?切换片段而不破坏它并再次创建它。

It works very well, but the problem is sometimes 2 fragments show at once time (I dont know why because I hide all fragments) Any other way to achieve that? Switch fragment without destroying it and creating it again.

推荐答案

使用 ViewPager 在这种情况下, FragmentPagerAdapter 适合你。

Using ViewPager with FragmentPagerAdapter suits for you in this case.

然后使用 ViewPager#setOffsetPageLimit(5)。这将帮助您显示/隐藏您的片段而无需再次重新创建它。

Then use ViewPager#setOffsetPageLimit(5). This will help you show/hide your fragments without recreating it again.

按照教程

试一试,然后告诉我你的问题是否解决了。 ;)

Let try it, then tell me if your problem is solved or not. ;)

这篇关于在Tabs android中添加片段的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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