Working with portrait and landscape mode programmatically in android

I want to create layouts in both portrait and landscape modes (in java) and programmatically change the orientation in the java file. Can anybody help me?

+4
source share
2 answers

you can programmatically force the orientation to be changed using the setRequestOrientation() method of the Activity class.

  public class Example extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //---change to landscape mode--- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } 

To switch to portrait mode, use the ActivityInfo.SCREEN_ORIENTATION_PORTRAIT constant:

For more information, see this .

EDIT

You can add orientation to your specific Activity in AndroidManifest.xml as follows:

  <activity android:name=".DemoActivity" android:label="@string/app_name" android:screenOrientation="portrait"> 

As for the layout, it is recommended to create different folders under res/ . For example, you can create res/layout-port for a portrait and res/layout-land for a landscape.

+2
source

Try the following:

 if(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // code to do for Landscape Mode } else { // code to do for Portrait Mode } 
0
source

All Articles