我有1个主片段容器和4个片段,我希望通过底部导航栏切换。我不希望每个片段在每次需要显示时都被重新加载(使用replace方法)。我尝试使用下面的代码加载一个片段(如果它以前没有加载)或者显示它(如果它已经加载)(并隐藏前一个)。出于某种原因,隐藏和展示似乎不起作用。
navigationView.setOnItemSelectedListener(item -> {
int itemId = item.getItemId();
Fragment fragment = getFragment(currentFragment);
if (itemId == R.id.groupChatsIconItem) {
if (fragment == null || fragment.getClass() != GroupChatFragment.class)
loadFragment(GROUP_CHAT_FRAGMENT);
} else if (itemId == R.id.friendsIconItem) {
if (fragment == null || fragment.getClass() != FriendsFragment.class)
loadFragment(FRIENDS_FRAGMENT);
} else if (itemId == R.id.myProfileActivityIconItem) {
if (fragment == null || fragment.getClass() != MyProfileFragment.class)
loadFragment(MY_PROFILE_FRAGMENT);
} else if (itemId == R.id.directChatIconItem) {
if (fragment == null || fragment.getClass() != DirectChatFragment.class)
loadFragment(DIRECT_CHAT_FRAGMENT);
}
return true;
});
}
public void loadFragment(String tag) {
//if that's the first fragment - not adding to back stack to make sure the navigation view isn't being displayed alone.
if (currentFragment == null) {
currentFragment = tag;
getSupportFragmentManager()
.beginTransaction()
.add(R.id.mainFragmentContainerView, getFragment(tag), tag)
.setReorderingAllowed(true)
.commit();
}
//The desired fragment isn't loaded yet. loading it
else if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
getSupportFragmentManager()
.beginTransaction()
.hide(getFragment(currentFragment))
.add(mainFragmentContainerView.getId(), getFragment(tag), tag)
.addToBackStack("yes")
.setReorderingAllowed(true)
.commit();
currentFragment = tag;
}
//fragment was already loaded - hide the current one and show the new one
else {
Log.d("banana","desired fragment is already loaded");
getSupportFragmentManager()
.beginTransaction()
.hide(getFragment(currentFragment))
.show(getFragment(tag))
.commit();
currentFragment = tag;
}
}
private Fragment getFragment(String tag) {
if (tag == null)
return null;
if (tag.equals(GROUP_CHAT_FRAGMENT))
return new GroupChatFragment();
if (tag.equals(FRIENDS_FRAGMENT))
return new FriendsFragment();
if (tag.equals(MY_PROFILE_FRAGMENT))
return new MyProfileFragment();
return new DirectChatFragment();
}
我不太清楚为什么隐藏和显示似乎不工作-每当我试图点击加载一个片段的第一次它被正确加载,但一旦我试图点击一个片段,已经加载,它只是不改变。我也试过把hide和load/show功能分离成两个不同的功能,但没有成功。任何帮助都会非常感谢:)
1条答案
按热度按时间f0brbegy1#
我发现了这个问题-而不是做
.hide(getFragment(currentFragment))
我应该做.hide(getSupportFragmentManager().findFragmentByTag(currentFragment))
因为我正在寻找隐藏的片段,目前正在加载的容器-而不是一个新的(getFragment返回一个新的片段给我)。