In my app, I have a FragmentActivity with multiple Fragments all in portrait mode except for one specific Fragment. I move between Fragments through footer Views in the FragmentActivity.
I have a different layout (actually have the same name but different widget Views) for this specific Fragment when there is an orientation change. When in landscape mode, I want to remove specific widgets from the Fragment layout View and the footer View of the FragmentActivity and when back in portrait, add everything back.
I have saved all the data I need in onSavedInstanceState() in the Fragment, but where best should I possibly test for an orientation change so that I can restore the Views appropriately?
Not sure I can override onConfigurationChange() and test there in my Fragment because I don't have the android:configChanges="orientation" in my android Manifest.
Use the following code line in the fragment where you want a specific (in this case portrait) orientation. getActivity(). setRequestedOrientation( ActivityInfo. SCREEN_ORIENTATION_PORTRAIT);
int orientation = display. getOrientation(); Check orientation as your way and use this to change orientation: setRequestedOrientation (ActivityInfo.
If the activity locks the display ( android:screenOrientation="portrait" ), this method will return the same value irrespective of how the user rotates the device. In that case you'd use the accelerometer or the gravity sensor to figure out orientation properly.
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.
Keep this check in onCreate(). When you rotate your device the app is restarted. So onCreate is called again when the app restarts.
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
// Landscape
}
else {
// Portrait
}
You can control the orientation change by overriding onConfigurationChanged function of your fragment as well.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
Log.v("TAG","Landscape !!!");
}
else {
Log.v("TAG","Portrait !!!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With