【发布时间】:2021-01-26 06:13:54
【问题描述】:
我想根据 OnClickListener 隐藏/显示片段。隐藏片段有效,但当我想再次显示它时,它不会出现。我不想使用 replace(),因为片段需要一段时间才能加载,因为它从服务器下载图像。
这是我的替换方法的代码:
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (addedFragments.size() != 0) {
for (Fragment frag :
addedFragments) {
if (frag !=null) {
String fragTag = frag.getClass().getName();
if (fragmentManager.findFragmentByTag(fragTag).isVisible() && !fragTag.equals(backStateName)) {
fragmentTransaction.hide(fragmentManager.findFragmentByTag(frag.getClass().getName()));
Log.d("frag", "hide" + fragTag);
}
}
}
}
if(fragmentManager.findFragmentByTag(backStateName) != null && fragmentManager.findFragmentByTag(backStateName).isAdded()) {
//if the fragment exists, show it.
fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out).show(fragmentManager.findFragmentByTag(backStateName)).commit();
Log.d("frag", "show frag"+fragmentManager.findFragmentByTag(backStateName).getClass().getName());
}
}
以及监听器的代码:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.option1) {
if (fragmentManager.findFragmentByTag(WantedAnimals.class.getName()) == null){
WantedAnimals wantedAnimals = new WantedAnimals();
fragmentManager.beginTransaction().add(R.id.container_fragment, wantedAnimals, wantedAnimals.getClass().getName()).commit();
addedFragments.add(wantedAnimals);
} else {
replaceFragment(fragmentManager.findFragmentByTag(WantedAnimals.class.getName()));
}
}
if (menuItem.getItemId() == R.id.option2) {
if (fragmentManager.findFragmentByTag(FoundAnimals.class.getName()) == null){
FoundAnimals foundAnimals = new FoundAnimals();
fragmentManager.beginTransaction().add(R.id.container_fragment, foundAnimals, foundAnimals.getClass().getName()).commit();
addedFragments.add(foundAnimals);
} else {
replaceFragment(fragmentManager.findFragmentByTag(FoundAnimals.class.getName()));
}
}
if (menuItem.getItemId() == R.id.option3) {
if (fragmentManager.findFragmentByTag(AnimalsToGiveAway.class.getName()) == null){
AnimalsToGiveAway animalsToGiveAway = new AnimalsToGiveAway();
fragmentManager.beginTransaction().add(R.id.container_fragment, animalsToGiveAway, animalsToGiveAway.getClass().getName()).commit();
addedFragments.add(animalsToGiveAway);
} else {
replaceFragment(fragmentManager.findFragmentByTag(AnimalsToGiveAway.class.getName()));
}
}
return true;
}
【问题讨论】:
标签: java android android-studio android-fragments android-fragmentactivity