setRetainInstance不起作用

时间:2016-06-12 03:36:45

标签: android android-studio fragment navigation-drawer

我使用导航抽屉切换两个片段。我在两个片段中都使用setRetainInstance(true),但它不起作用。在FeedFragment中有一个简单的textView,在MapFragment中有一个谷歌地图。

FeedFragment和MapFragment(onCreate中的相同代码)

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

MainActivity

public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    Fragment fragment = null;
    if (id == R.id.nav_feed) {
        if (feedFragment == null)
            feedFragment = new FeedFragment();
        fragment = feedFragment;
    } else if (id == R.id.nav_mapa) {
        if (mapFragment == null)
            mapFragment = new MapFragment();
        fragment = mapFragment;
    }

    try {
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
    } catch (Exception e) {
        e.printStackTrace();
    }

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

修改

我找到了解决方案。我将replace函数中的片段更改为feedFragment或mapFragment。

if (id == R.id.nav_feed) {
    if (feedFragment == null)
        feedFragment = new FeedFragment();
    fragmentManager.beginTransaction().replace(R.id.content_frame, feedFragment).commit();
} else if (id == R.id.nav_mapa) {
    if (mapFragment == null)
        mapFragment = new MapFragment();
    fragmentManager.beginTransaction().replace(R.id.content_frame, mapFragment).commit(); 
}

0 个答案:

没有答案