Reputation: 6258
I need to detect screen orientation change on a fragment and to do so, I am currently using this method:
public void onEvent(OrientationEvent event){...}
which works absolutely fine on my Nexus 4. The problem I have is that on a Samsung Galaxy S3, the method is not called when rotating the screen. Anybody has an idea?
Many thanks.
Upvotes: 0
Views: 3659
Reputation: 8478
You need to override the method onConfigurationChange() in your fragment simplly. You can have look at this developer android post :
public void onConfigurationChanged (Configuration newConfig)
Called by the system when the device configuration changes while your component is running. Note that, unlike activities, other components are never restarted when a configuration changes: they must always deal with the results of the change, such as by re-retrieving resources.
At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.
Parameters
newConfig The new device configuration.
Inside onConfigurationChanged, You need to check the current orientation like :
newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
newConfig.orientation == Configuration.ORIENTATION_PORTRAIT
and add logic
Upvotes: 0
Reputation: 6215
There is a good Google webpage on this @ Handling Runtime Changes. This covers when user changes screen between horizontal/vertical view, and switching applications. Code snippet:
@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();
}
}
The code above can be placed in the Activity or the Fragment subclass.
In your manifest xml, you set:
<activity android:name=".MyActivity"
android:configChanges="orientation">
Please keep us posted, I would like to know of your progress. Someday I may want to do this also. And I would code it like this, if I do
Upvotes: 1
Reputation: 37
private String getScreenOrientation(){
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
return "ORIENTATION_PORTRAIT";
else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
return "ORIENTATION_LANDSCAPE";
else
return "";
}
Upvotes: 0