使用viewmodel旋转时如何保持相同的片段?

时间:2019-06-20 18:13:59

标签: android android-fragments mvvm kotlin

我有一个底部导航视图,上面有3个按钮(受欢迎,发现,收藏)。每个片段都显示自己的片段(popularFragment,discoverFragment,favoriteFragment)。应用程序首次运行时,默认情况下会显示PopularFragment,如果我单击“发现”或“收藏夹”按钮,则会显示他们自己的片段,这绝对是我想要的,但是问题是如果旋转发生变化,popularFragment会再次显示。

我想用viewModel解决这个问题,但是我是Android架构的新手。这是我的代码:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        popularFragment = FragmentPopular()
        discoverFragment = FragmentDiscover()
        favoritesFragment = FragmentFavorites()

        setFragment(popularFragment)

        navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
    }

    fun setFragment(fragment: Fragment){
        supportFragmentManager.beginTransaction().replace(R.id.frame_main, fragment).commit()
    }

那我该如何使用viewModel解决这个问题?

1 个答案:

答案 0 :(得分:0)

在您的情况下,您可以将数据放入包中,然后检查包!= null

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putString("name", "David");
    outState.putInt("age", 17);
}

将此检查添加到onCreate()

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    …
    if(savedInstanceState != null)
    {
         savedInstanceState.getString("name");
         savedInstanceState.getInt("age");
    }
}

或者您可以通过以下方式做到这一点:

将此配置添加到您的活动中:

<activity android:name=".com.somepackage.MyActivity"
    android:configChanges="orientation|screenSize|keyboardHidden" > </activity>

然后将您的编辑文本值更改为onSaveInstanceState

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
     outState.putCharSequence(KEY_TITLE, et_text.getText().toString());
 }

然后通过onViewStateRestored

获取保存的值
 @Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);

    String savedTitle = null;
    if (savedInstanceState != null) {
        savedTitle = savedInstanceState.getString(KEY_TITLE);
        et_text.setText(
    }
}