当屏幕旋转时没有保存当前的片段和数据

时间:2016-11-12 04:57:40

标签: java android android-fragments

我是初学者,我不明白,请帮忙。我有NavigationView和几个页面片段。问题:如果我将方向更改为横向,则将其移动到主屏幕的数据重置。你是如何解决这个问题的?

代码MainActivity.Oncreate()

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
   //removed unnecessary codes
    navigationView.setNavigationItemSelectedListener(this);
    transaction.beginTransaction().replace(R.id.container, fragment_main).commit();
}

和void导航视图的导航ItemSelected()

switch (item.getItemId())
 {
     case R.id.nav_main :
  transaction.beginTransaction().replace(R.id.container,fragment_main).commit();
         break;
     case R.id.nav_report_category:
         transaction.beginTransaction().replace(R.id.container,fragment_category).commit();
         break;

     case R.id.nav_history:
         transaction.beginTransaction().replace(R.id.container,fragment_history).commit();
         break;
 }

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

1 个答案:

答案 0 :(得分:1)

您需要实施savedInstanceState()方法。在那里,您可以使用onCreate方法提取视图:

public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        savedInstanceState.getString("param");
    }
}
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //Save your fragment data here like so...
    outState.putString("param", value);

}

我还建议您阅读有关onSavedInstanceState方法的Android文档以及如何重新创建活动here。我还建议你阅读这篇文章:https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en