当活动由于导航抽屉活动中的方向更改而重新启动时,如何保留相同的片段 [英] How to keep the same fragment when activity restarts due to orientation change in a Navigation Drawer Activity

查看:109
本文介绍了当活动由于导航抽屉活动中的方向更改而重新启动时,如何保留相同的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现许多帖子解释了如何从savedInstanceState Bundle中获取Fragment,但是,由于Activity可以在4个Fragments之间交换,我需要一种方法来了解哪个片段还活着,然后在开始改变方向时旋转.

I found many post explaining how get the Fragment from the savedInstanceState Bundle but, because the Activity can swap between 4 Fragments, i need a way to know which Fragment was alive before rotate when the orientation started to change.

我有几个片段的原因是因为我使用的是导航抽屉,所以每个菜单项都是一个片段.

The reason i have several Fragments is because i am using Navigation Drawer, so each menu item as a fragment.

推荐答案

找到了我自己的答案,那毕竟是一件非常简单的事情.我将解决方案留给了像我这样不熟悉android的人.

Found my own answer and it it was a really simple thing after all. I left the solution here for those who are not familiar to android,like me .

//current fragment
int fragment_id;

//make fragment selection available form the menu resource id
private void setFragment(MenuItem item) {

    Fragment fragment = null;
    fragment_id = item.getItemId();

    switch (fragment_id) {
        case R.id.nav_option_1:
            fragment = MyFragment1.newInstance(true);
            break;
        ...
        //Set fragment
        FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.replace(R.id.content_navigation, fragment);
        t.commit();
    }

    item.setChecked(true);
}

private class DrawerItemClickListener implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        setFragment(item);
        return false;
    }
}

//save the state
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(SAVE_INSTANCE_FRAGMENT_KEY, fragmentid);
}

//restore the saved fragment on create
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation);
    ///...
    if (savedInstanceState != null) {
        int fragment_id = savedInstanceState.getInt(SAVE_INSTANCE_FRAGMENT_KEY);
        selectItem(mDrawerList.getMenu().findItem(fragment_id));
    } else {
        selectItem(mDrawerList.getMenu().findItem(R.id.home_fragment_id));
    }

}

这篇关于当活动由于导航抽屉活动中的方向更改而重新启动时,如何保留相同的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆