Ispas Claudiu
Ispas Claudiu

Reputation: 1998

getConfiguration().orientation doesn't work in Android Fragment

I try to get the screen orientation in an Android Fragment using getResources().getConfiguration().orientation but it returns the same result even though I rotated the device in portrait and landscape mode. I also used in in onConfigurationChanged() (see code below) and the configuration received as parameter reports the corect screen orientation but the generic method of getting the screen orientation always reports the same orientation mode in which the activity started(either landscape or portrait).

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
        Log.e(TAG, "NEW CONFIG: ORIENTATION_LANDSCAPE");
    else
        Log.e(TAG, "NEW CONFIG: ORIENTATION_PORTRAIT");

    Configuration config = getResources().getConfiguration();
    if(config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Log.e(TAG, "config: PORTRAIT");
    else
        Log.e(TAG, "config: LANDSCAPE");


    LayoutInflater inflater = LayoutInflater.from(getActivity());
    populateViewForOrientation(inflater, (ViewGroup)getView());
}

For example if the activity started in landsape mode the first log output will be:

1.a "NEW CONFIG: ORIENTATION_LANDSCAPE"

1.b "config: LANDSCAPE"

after I rotate the device in portrait mode:

2.a "NEW CONFIG: ORIENTATION_PORTRAIT"

2.b "config: LANDSCAPE"

As you can notice, the config reports the same orientation mode even though the device has different orientation mode.

So what is happening here? Thank you! :)

Upvotes: 3

Views: 2183

Answers (1)

Ilya Gazman
Ilya Gazman

Reputation: 32271

Some times the easy solution is not to fight the system and just to accept the facts as they are. Just update the configuration as they change.

Try this:

private Configuration configuration;

private int getOrientation(){
    return getConfiguration().orientation;
}

private Configuration getConfiguration(){
    if (configuration == null) {
        configuration = getResources().getConfiguration();
    }
    return configuration;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    configuration = newConfig;
}

Upvotes: 1

Related Questions