我試圖加載一個新的片段,當一個方法被調用。這種方法創建一個新的片段,並「替換」其他片段:Android:片段backStack
private void showTestFragment(Fragment oldFragment, boolean addBackStack, BaseAdapter adapter, int position) {
Cursor cursor = (Cursor)adapter.getItem(position);
if(cursor != null){
int idx = cursor.getColumnIndexOrThrow(Episode._ID);
long rowId = cursor.getLong(idx);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(oldFragment != null){
Log.i(TAG, "Removing the old fragment");
fragmentTransaction.remove(oldFragment);
}
TestFragment testFragment = new TestFragment();
testFragment.setId(rowId);
fragmentTransaction.add(android.R.id.content, testFragment);
if(addBackStack){
Log.i(TAG, "Added to the backstack");
fragmentTransaction.addToBackStack(TAG);
}
fragmentTransaction.commit();
Fragment f = getFragmentManager()
.findFragmentById(R.id.index);
Log.i(TAG, "after commit, frag is "+ f);
}
}
這工作正常,直到我回去。當我回去時應該刪除最後一個片段。之前我要去實現對活動
public void onBackPressed(){}
方法來刪除最後一個片段,我想知道如果我正確處理片段變化。它看起來像我在這裏失去了一些東西..
的可能的複製[如何實現片段onBackPressed()?](http://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments) –