我正在使用 MainActivity 来管理几个片段的显示。我有一个 showFragment 方法,它遍历我的片段数组并显示/隐藏它们,并相应地设置回栈。问题是每当我按下返回按钮时,HomeFrag 就会显示出来,所有其他碎片都堆积在下面。我从文档中得到的印象是后退按钮将撤消最后一个事务(在提交之前添加的任何内容)。谁能解释为什么这可能会导致这种意外行为?这是我的主要活动。片段都定义在activity_main.xml中:
public class MainActivity extends MenuBaseActivity {
private static final int HOME = 0;
private static final int WRITE = 1;
private static final int UPLOAD = 2;
private static final int SHARE = 3;
private static final int SNAP = 4;
private static final int POSITION = 5;
private static final int FRAGMENT_COUNT = POSITION + 1;
/** The current fragment being displayed **/
private int mCurrentFragment = -1;
private Fragment[] fragments = new Fragment[FRAGMENT_COUNT];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
fragments[HOME] = fm.findFragmentById(R.id.homeFrag);
fragments[WRITE] = fm.findFragmentById(R.id.writeFrag);
fragments[UPLOAD] = fm.findFragmentById(R.id.uploadFrag);
fragments[SHARE] = fm.findFragmentById(R.id.shareFrag);
fragments[SNAP] = fm.findFragmentById(R.id.snapFrag);
fragments[POSITION] = fm.findFragmentById(R.id.positionFrag);
// If no fragments are currently being displayed, show the home frag
if(mCurrentFragment == -1) {
showFragment(0,true);
}
}
/*
* Handles the click event for all navigation buttons (navOnClick) in the fragments.
*/
//TODO: Tag navigation with text strings instead of integers
public void navOnClick(View v) {
Object objectTag = v.getTag();
int tag = Integer.valueOf(objectTag.toString());
showFragment(tag, true);
}
public void showFragment(int fragmentIndex, boolean addToBackStack) {
Log.v(Constants.getLogTag(), "Main: fragmentIndex:" + fragmentIndex + " backstack:" + addToBackStack);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
ft.show(fragments[i]);
} else {
ft.hide(fragments[i]);
}
}
if (addToBackStack) {
Log.v(Constants.getLogTag(), "Main: Adding to backstack");
ft.addToBackStack(null);
}
//Update the current fragment identifier
mCurrentFragment = fragmentIndex;
ft.commit();
}
}