如何在 Android 中的特定片段容器中显示片段
Posted
技术标签:
【中文标题】如何在 Android 中的特定片段容器中显示片段【英文标题】:How to show a fragment inside a specific Fragment Container in Android 【发布时间】:2022-01-10 11:16:27 【问题描述】:每当我想根据我使用的所选项目更改片段时:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
但是现在我想做它,这样我就可以简单地显示不同的片段而不是每次重新选择它们时都创建新的片段,所以我找到了.show
而不是.replace
,但是@987654324的问题@ 是我不能声明我希望该片段显示在哪里......或者我可能做错了:
getSupportFragmentManager().beginTransaction().show(fragment).commit();
【问题讨论】:
【参考方案1】:如果你想使用 show/hide 方法,你需要在这之前添加一个片段,因为你可以看到容器在这里可用。我只是展示了如何显示或隐藏一个片段的示例。如果您有很多片段,例如您可以保存列表,然后将其他片段隐藏在循环中。如果有兴趣,我从下面添加。
public void showFragment(Fragment fragment)
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (fragment.isAdded())
fragmentTransaction.show(fragment);
else
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
public void hideFragment(Fragment fragment)
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (fragment.isAdded())
fragmentTransaction.hide(fragment);
fragmentTransaction.commit();
如果有很多片段
public class MainActivity extends AppCompatActivity
HashMap<String, Fragment> fragments = new HashMap<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* call this method when you want to add a new fragment
* Example: addFragment(new A(), "TAG_A")
* */
public void addFragment(Fragment fragment, String fragmentTag)
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
/*Before add fragment we hide others*/
for (String fTag : fragments.keySet())
Fragment fragmentInStack = fragments.get(fTag);
if (fragmentInStack.isAdded() && !fragmentInStack.isHidden())
fragmentTransaction.hide(fragmentInStack);
if (!fragment.isAdded())
fragments.put(fragmentTag, fragment);
fragmentTransaction.add(R.id.container, fragment, fragmentTag);
else
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
/*
* call this method when you want to show fragment which are on the list
* Example: We have current fragment C and you want to show fragment A, that to call showFragment("TAG_A")
* */
public void showFragment(String fragmentTag)
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
/*hide others fragment besides the one we need to show*/
for (String fTag : fragments.keySet())
Fragment fragmentInStack = fragments.get(fTag);
if (!fTag.equals(fragmentTag) && fragmentInStack.isAdded())
fragmentTransaction.hide(fragmentInStack);
Fragment fragment = fragments.get(fragmentTag);
if (fragment != null && fragment.isAdded())
fragmentTransaction.show(fragment);
fragmentTransaction.commit();
【讨论】:
以上是关于如何在 Android 中的特定片段容器中显示片段的主要内容,如果未能解决你的问题,请参考以下文章