Arthur Attout
Arthur Attout

Reputation: 2916

Prevent layout change and still catch onConfigurationChanged

I need to lock the layout for a fragment in order to prevent it from rotating when the device is rotated to landscape.

To do that, I locked it in the manifest:

android:screenOrientation="portrait

The layout doesn't change, but I still need to do some work when the orientation is changed (rotate the buttons). Locking it this way prevents onConfigurationChanged from being called.

The behavior I'm aiming is exactly like the default camera app. When you rotate the device, the layout stays the same, but only the buttons rotate.

Has anyone a trick to do this?

Upvotes: 1

Views: 842

Answers (2)

rafsanahmad007
rafsanahmad007

Reputation: 23881

If you want to listen for simple screen orientation changes programmatically and have your application react to them, you can use the OrientationEventListener class to do this within your Activity.

Implementing orientation event handling in your Activity is simple. Simply instantiate an OrientationEventListener and provide its implementation. For example, the following Activity class called SimpleOrientationActivity logs orientation information to LogCat:

public class SimpleOrientationActivity extends Activity {
    OrientationEventListener mOrientationListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mOrientationListener = new OrientationEventListener(this,
            SensorManager.SENSOR_DELAY_NORMAL) {

            @Override
            public void onOrientationChanged(int orientation) {
                Log.v(DEBUG_TAG,
                    "Orientation changed to " + orientation);
            }
        };

       if (mOrientationListener.canDetectOrientation() == true) {
           Log.v(DEBUG_TAG, "Can detect orientation");
           mOrientationListener.enable();
       }
       else {
           Log.v(DEBUG_TAG, "Cannot detect orientation");
           mOrientationListener.disable();
       }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mOrientationListener.disable();
    }
}

For more help, see this.

Also this answer will help.

Upvotes: 2

Dishonered
Dishonered

Reputation: 8851

You can set the orientation programmatically:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);

And detect orientation changes in code using this:

 @Override
 public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
     // Do something here...
 }

Upvotes: -1

Related Questions