简体   繁体   中英

How to keep the same fragment when rotation changes with using viewmodel?

I have a bottom navigation view with 3 buttons(popular,discover,favorite) on it. Each one shows their own fragments (popularFragment,discoverFragment,favoriteFragment). When app runs for the first time, it shows popularFragment by default and if i click discover or favorite buttons, their own fragments shows up and that is absolutely what i want but the problem is if rotation changes, popularFragment shows again.

I want to solve that problem with viewModel but i'm totaly new to Android architecture. This is my code:

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()
    }

So how can i solve this problem with using viewModel?

In your case you can do it with putting your data to the bundle and then check bundle != null

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

Add this check to your onCreate()

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

Or you can do it in this way:

Add this config to your activity:

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

Then your edit text values to onSaveInstanceState

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

And get your saved values through 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(
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM