我正在尝试关闭片段,并希望通过在片段实现中使用addToBackStack来恢复主要活动,但是它无法正常工作。后退按钮正在关闭应用程序。

我正在使用的片段实现方法是,

  private void dispaySelectedScreen(int id) {
    Fragment fragment = null;

    switch (id) {
        case R.id.facebook_login:
            fragment = new FacebookLogin();
            break;
        case R.id.memes:
            fragment = new Memes();
            break;
        case R.id.submit_image:
            fragment = new SubmitImage();
            break;
        case R.id.discussion:
            fragment = new Discussions();
            break;
        case R.id.invite:
            fragment = new Invite();
            break;
        case R.id.connect_fb:
            fragment = new FacebookConnect();
            break;
        case R.id.connect_twitter:
            fragment = new TwitterConnect();
            break;
        case R.id.connect_instagram:
            fragment = new InstaConnect();
            break;
    }

    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_main, fragment);
        ft.addToBackStack(null);
        ft.commit();




    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);


我还为抽屉声明了一个onBackPressed方法,

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }


    }


请提出建议。

最佳答案

fragment.addToBackStack(null)足以打开上一个活动,但是如果您要对后退进行一些操作(除了移除片段之外),那么我们将覆盖onBackPressed(),因此这是我经过测试的方法,请看一下:

下面是我的实现:



@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, new MyFragment(), "MY_FRAG")
                .addToBackStack(null).commit();
    }

    @Override
    public void onBackPressed() {
        MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("MY_FRAG");
        if (fragment != null) {
            if (fragment.isVisible()) {
                //todo perform any action if you want when fragment is removed
            }
        } else {
            super.onBackPressed();
        }
    }

10-08 13:46