[英]What is the best way to add fragment in the Tabs android
我的應用程序有一個底部導航欄,其中有5個標簽。 因此,根據這些選項卡,我有5個片段當我單擊選項卡時,片段會根據該選項卡進行更改。 我可以使用beginTransaction()。replace方法來切換片段。我不希望每次切換標簽時都破壞片段並重新創建,所以我的解決方案是這樣的
//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個片段(我不知道為什么,因為我隱藏了所有片段)還有其他方法可以實現嗎? 切換片段而不破壞它並再次創建它。
為了添加片段,我為我的項目編寫了這段代碼,希望對您有所幫助。
public static void replaceFragment(Fragment fragment, FragmentManager fragmentManager) {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
Fragment currentFrag = fragmentManager.findFragmentById(R.id.frame_container);
Log.e("Current Fragment", "" + currentFrag);
// boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);
int countFrag = fragmentManager.getBackStackEntryCount();
Log.e("Count", "" + countFrag);
if (currentFrag != null && currentFrag.getClass().getName().equalsIgnoreCase(fragment.getClass().getName())) {
return;
}
FragmentTransaction ft = fragmentManager.beginTransaction();
// if (!fragmentPopped) {
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(backStateName);
ft.commit();
// }
currentFrag = fragmentManager.findFragmentById(R.id.frame_container);
Log.e("Current Fragment", "" + currentFrag);
}
希望對您有所幫助,並在整個項目中使用此方法替換片段。
在這種情況下,適合將ViewPager
與FragmentPagerAdapter
一起使用。
然后使用ViewPager#setOffsetPageLimit(5)
。 這將幫助您顯示/隱藏片段,而無需再次創建。
遵循本教程
讓我們嘗試一下,然后告訴我您的問題是否解決。 ;)
您不必隱藏片段,只需像下面的方法那樣替換片段即可:
public void setFragment(Fragment fragmentWhichYouWantToShow) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
ft.replace(R.id.container, fragmentWhichYouWantToShow);
ft.commit();
}
嘗試以單筆交易進行交易。
protected void showAsRootFragment(Fragment fragment, @NonNull String tag) {
FragmentManager supportFragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = supportFragmentManager.beginTransaction();
if (supportFragmentManager.getFragments() != null) {
for (Fragment attachedFragment : supportFragmentManager.getFragments()) {
if (attachedFragment != null && !tag.equals(attachedFragment.getTag())) {
transaction.hide(attachedFragment);
attachedFragment.setUserVisibleHint(false);
}
}
}
if (!fragment.isAdded()) {
transaction.add(R.id.frame_container, fragment, tag);
fragment.setUserVisibleHint(true);
} else {
transaction.show(fragment);
fragment.setUserVisibleHint(true);
}
transaction.commit();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.