清除后备堆栈/历史导航抽屉项目已选中

时间:2014-02-18 10:25:43

标签: android android-fragments navigation navigation-drawer

在MainActivity中,我有一个如下所示的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。 我已经尝试了解决这里发现的类似问题的大多数解决方案,但到目前为止,不幸的是没有任何对我有用。

有没有人能解决这个问题?

2 个答案:

答案 0 :(得分:0)

像这样使用android.support.v4.content.IntentCompat:

Intent intent = IntentCompat.makeRestartActivityTask(new ComponentName(DrawerActivity.this, Tracksfragment.class));
startActivity(intent);

答案 1 :(得分:-1)

您可以在启动另一项活动时在意图中设置以下标志:

    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);

希望这就是你要找的东西。

相关问题