Use ViewModel to rotate Android apps roughly

It is troublesome to think about what to do when the Activity is destroyed if you seriously support rotation, but if you want to handle rotation roughly aside from the details, ViewModel It's easy to do with / topic / libraries / architecture / viewmodel).

how can I do?

Before rotation

For example, suppose you have an Activity that displays the number of rotations in Toast each time it rotates in the following form.


public class MainActivity extends AppCompatActivity {

    //I want to keep this value even if I rotate it
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        count++;
        Toast.makeText(this, String.valueOf(count) + "The second time! !!", Toast.LENGTH_SHORT).show();
    }
}

When this code is executed, "1st time !!" is displayed no matter how many times it is rotated. This is because every time it is rotated, it starts over from onCreate () and count is initialized.

After rotation

If you include Architecture Compoennts provided by Google, you can easily rotate it.

Make app / build.gradle the following.

dependencies {
    ...
    compile 'android.arch.lifecycle:extensions:1.1.1'
    ...
}

Since the above library is only in the google repository, you need to make changes to build.gradle in the project root as follows.

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }
    }
}

You can now use Architecture Components. All you have to do now is change the Activity as follows.


public class MainActivity extends AppCompatActivity {

    //Push the variable you want to keep into the ↓ ViewModel!
    public static class MyModel extends ViewModel {
        int count = 0;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Extract the Model defined above from ViewModelProviders
        //The value before rotation is properly retained in the model taken out here.
        MyModel model = ViewModelProviders.of(this).get(MyModel.class);
        model.count++;
        Toast.makeText(this, String.valueOf(model.count) + "The second time! !!", Toast.LENGTH_SHORT).show();
    }
}

Make the variable you want to keep after rotation a member variable called ViewModel, and just pull it out from ViewModelProvider to rotate it. Correspondence is completed. Easy!

Of course, Fragment can handle it in the same way.

ViewModel also releases it according to the life cycle, so you don't have to worry about leaks. However, be aware that if you put a View or Context in a ViewModel, it will leak.

It should be noted that the Activity may be destroyed when the app is in the background and left for a while, but in that case count returns to the initial value (0 in this code). I will end up.

If you want to support it properly, you need to support rotation using saveInstanceState, Room, etc.

References

Recommended Posts

Use ViewModel to rotate Android apps roughly
Easy to use Cloud Firestore (Android)
Convert all Android apps (Java) to Kotlin
How to use ExpandableListView in Android Studio
How to use UsageStatsManager in Android Studio (How to check the startup time of other apps)
How to use Truth (assertion library for Java / Android)
[Android Studio] I want to use Maven library on Android
[Note] Challenge to develop Android application for business use
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use java.util.logging
How to use map
How to use collection_select
PATH to use docker-slim
Introduction to Android Layout
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use Mali Graphics Debugger to debug apps for Android (even those made with + Unity)
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
How to use OpenCV 4 on Android and view camera live view
Use Java included with Android Studio to build React Native
How to fix Android apps crashing with RenderThread mystery error