In android there are different orientations for screen. While rotating the phone android has a default property of changing the orientation from portrait to landscape or vice versa. In this tutorial we will learn how to change the orientation on a button click without rotation the phone.
It can be simply achieved by making use of setRequestedOrientation method in android. In this example we will have a button and while clicking on button it will change to landscape if it is in portrait mode and vice versa if it is in landscape mode.
To start , just add the below code to your layout for adding a button to your screen.
<Button android:id="@+id/btn_change_orientation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="orient"/>
Now use the below code in your activity
Button btn_change_orientation = (Button) findViewById(R.id.btn_change_orientation); btn_change_orientation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int orientation = getResources().getConfiguration().orientation; if(orientation == Configuration.ORIENTATION_PORTRAIT){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else{ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } });