我完全陷入了以下问题。
我有五个Fragments
。
FragA
和FragB
。
从包含两个条目的选项菜单中我想:
menuEntryA
:显示/添加FragC
并移除/隐藏/取消FragD
和FragE
menuEntryB
:显示/添加FragD
和FragE
并删除/隐藏/分离FragC
Fragments
/类仍然可以存在,但不能显示它们。
我达到的只是Fragment
变为白色,但它仍然占据Fragment
列表中的位置,当向前向后滑动Fragments
时,它再次出现。
这是我的代码,请给我提示填写必要的代码。我在这方面工作了好几个小时,但我没有取得任何成功。
private void setupViewPager(CustomViewPager viewPager) {
mAdapter = new ViewPagerAdapter(getSupportFragmentManager());
fragA = new FrgA();
fragB = new FrgB();
fragC = new FrgC();
fragD = new FrgD();
fragE = new FrgE();
mAdapter.addFragment( fragA, getString(R.string.frag_title_A));
mAdapter.addFragment( fragB, getString(R.string.frag_title_B));
mAdapter.addFragment( fragC, getString(R.string.frag_title_C));
mAdapter.addFragment( fragD, getString(R.string.frag_title_D));
mAdapter.addFragment( fragE, getString(R.string.frag_title_E));
viewPager.setAdapter(mAdapter);
viewPager.setCurrentItem(1);
viewPager.setPagingEnabled(true);
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> myFragmentList = new ArrayList<>();
private final List<String> myFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return myFragmentList.get(position);
}
@Override
public int getCount() {
return myFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
boolean found = false;
for (int i = 0; i < myFragmentList.size(); i++) {
if (myFragmentList.get(i).getClass().getName().equalsIgnoreCase(fragment.getClass().getName())) {
found = true;
}
}
if (!found) {
myFragmentList.add(fragment);
myFragmentTitleList.add(title);
}
}
@Override
public CharSequence getPageTitle(int position) {
return myFragmentTitleList.get(position);
}
}
protected void optionsMenuA() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragCustomtext);
//ft.detach(fragCustomtext);
ft.commit();
fm.popBackStack("null", FragmentManager.POP_BACK_STACK_INCLUSIVE);
//show/add FragC
//remove/hide/detatch FragD
//remove/hide/detatch FragE.
}
protected void optionsMenuB() {
//show/add FragD
//show/add FragE
//remove/hide/detatch FragC
}
<?xml encoding="utf-8"version="1.0"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="eu.angermayr.test.MainActivity">
<eu.angermayr.test.CustomViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="0dp" />
</eu.angermayr.test.CustomViewPager>
</LinearLayout>