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).
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.
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.
Recommended Posts