You could set the onConfigurationChange()
method. To do that you need to override it in your Activity's code and set a few parameters in your Manifest:
MainActivity.java
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
You have to add these attributes (android:configChanges="orientation|screenSize"
) to your activity, set as many as you want to handle:
AndroidManifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation|screenSize"
android:label="@string/app_name">
Be careful, with this setup, your activity will not restart, as mentioned in the docs, so, if you want to restart it you will need to implement a manual restart.
Now, when one of these configurations change, MyActivity does not
restart. Instead, the MyActivity receives a call to
onConfigurationChanged().
Link to the main documentation.