我有3个fragmentfragmentA,fragmentB,fragmentC,默认情况下会在create的活动中添加该片段,以使其保持实例,之后,我还有另一个fragmentX,要在按钮容器上单击BackStack,在Button单击时将其添加到fragment容器中,fragmentX显示在添加,但是当我需要再次显示它不起作用时。
public class MainActivity extends ActivityBaseClass {
private Fragment fragmentA;
private Fragment fragmentB;
private Fragment fragmentC;
private Fragment fragmentX;
@BindView(R.id.btn_show_fragmentx)
Button mBtnShowFragmentX;
@BindView(R.id.tab_layout)
TabLayout mTab;
private FragmentTransaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentA = FragmentA.newInstance();
fragmentB = FragmentB.newInstance();
fragmentC = FragmentC.newInstance();
transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragmentA, "A");
transaction.add(R.id.fragment_container, fragmentB, "B");
transaction.add(R.id.fragment_container, fragmentC, "C");
transaction.commit();
mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
transaction = getSupportFragmentManager().beginTransaction();
switch (tab.getPosition()) {
case 0:
transaction.show(fragmentA);
transaction.hide(fragmentB);
transaction.hide(fragmentC);
break;
case 1:
transaction.show(fragmentB);
transaction.hide(fragmentA);
transaction.hide(fragmentC);
break;
case 2:
transaction.show(fragmentC);
transaction.hide(fragmentA);
transaction.hide(fragmentB);
break;
}
transaction.commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@OnClick(R.id.btn_show_fragmentx)
public void showFragmentX() {
if (fragmentX == null) {
fragmentX = FragmentX.newInstance();
transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragmentX, "X");
transaction.addToBackStack("X");
transaction.commit();
} else {
transaction = getSupportFragmentManager().beginTransaction();
transaction.show(fragmentX);
transaction.addToBackStack("X");
transaction.commit();
}
}
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
transaction = getSupportFragmentManager().beginTransaction();
transaction.hide(fragment);
transaction.commit();
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
最佳答案
调用onBackPressed
时,fragmentX被破坏。您需要检查Backstack的当前片段(如果它是FragmentX的实例),然后将其隐藏(并且不要弹出Backstack),否则请执行代码。