简体   繁体   中英

Working with portrait and landscape mode programmatically in android

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

you can programmatically force a change in orientation 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 change to portrait mode, use the ActivityInfo.SCREEN_ORIENTATION_PORTRAIT constant:

For more information, refer this .

EDIT

you can add orientation to your specific Activity in AndroidManifest.xml like this:

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

As far as Layouts are concerned, it is best advised to create different folders under res/ . For example, you can create res/layout-port for portrait and res/layout-land for landscape.

Try this:

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

        // code to do for Portrait Mode  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM