已经弄清楚如何在堆栈中向前和向后导航:
对于前向导航,如果下一个片段已经存在,则使用 hide() 和 show() 方法:
Button button = (Button)findViewById(R.id.new_fragment);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CountingFragment currentFragment = (CountingFragment)getFragmentManager().findFragmentByTag(String.valueOf(currentPositionInTheStack));
int nextLevel = currentPositionInTheStack+1;
currentPositionInTheStack++;
CountingFragment nextFragment = (CountingFragment)getFragmentManager().findFragmentByTag(String.valueOf(currentPositionInTheStack));
if (nextFragment == null) {
addFragmentToStack();
}
else
{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.hide(currentFragment);
fragmentTransaction.show(nextFragment);
fragmentTransaction.commit();
}
}
});
对于后退导航,必须重写 onBackPressed 方法:
public void onBackPressed() {
super.onBackPressed();
currentPositionInTheStack--;
Log.d("Current Position In The Stack", String.valueOf(currentPositionInTheStack));
if (currentPositionInTheStack ==0) {
//do smth
} }
原始问题中的 Fragment 是 NULL 并且应该是 null,但是,为什么它返回 Object ,如果我确实 getFragmentManager().findFragmentByTag("3"),例如,尚不清楚。