在MainActivity我有NavigationDrawer看起來像這樣:清晰堆棧中/歷史navigationdrawer項目選擇
private void displayView(int position) {
ListFragment listFragment = null;
switch (position) {
case 0:
listFragment = new AlbumFragment();
break;
case 1:
listFragment = new TrackFragment();
break;
default:
break;
}
if (listFragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, listFragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
在我的AlbumFragment我可以通過點擊listItems中切換到TrackFragment。
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// get album & artist of selected album
String album = ((TextView) v.findViewById(R.id.albumTitle)).getText().toString();
String artist = ((TextView) v.findViewById(R.id.albumArtist)).getText().toString();
String[] albumFilter = {"albumFilter", album, artist};
// Create new fragment and transaction
Fragment newFragment = new TrackFragment();
Bundle args = new Bundle();
args.putStringArray("filter", albumFilter);
newFragment.setArguments(args);
FragmentTransaction transaction = this.getActivity().getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
現在發生以下問題:如果我按Backbutton一切都很好,我回到了AlbumFragment。但是,如果我打開NavigationDrawer並選擇Tracksfragment,然後按下Backbutton,我會回到AlbumFragment,在它後面仍然是我的TrackFragment。
更多解釋:當我在AlbumFragment中選擇一個專輯時,只會顯示此專輯中的曲目。如果我從NavDrawer中選擇曲目,則會顯示所有曲目。
所以基本上我只需要從NavDrawer中選擇一個項目就清理整個Backstack-History。 我已經嘗試了大多數解決方案來解決這裏發現的類似問題,但unfortuneatley到目前爲止沒有任何工作。
有沒有人有這個問題的解決方案?
我想這可能是那麼容易,因爲加入這一行:'fm.popBackStackImmediate();' 在提交事務之前我的MainActivity。這樣做後,我也檢查了BackStackEntryCount,它在0,所以它的工作原理。 問題是我得到由AlbumFragment引起的NullpointerException。我不知道爲什麼它在我使用popBackStack()後被執行() – f4b