Adjusting layout Orientation with the device orien

2019-08-29 19:10发布

问题:

I wanted to know how i could change my LinearLayout orientation according to the device Orientation in JAVA, i found how to do it by the XML way with layout and layout-land but i didn't find how doing it by the java way.

Thank you very much.

回答1:

See this it describes how to Detect Orientation Changed then change orientation in java

In onCreate()

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

     setContentView(R.layout.activity_main);
     linearlayout=........;

     if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
     // landscape
     linearlayout.setOrientation(LinearLayout.HORIZONTAL); 
     }
     else {
    // portrait  
    linearlayout.setOrientation(LinearLayout.VERTICAL); 
     }
     ....
    }

and in onConfigurationChanged()

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

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
       // landscape
       linearlayout.setOrientation(LinearLayout.HORIZONTAL);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
     //  portrait
        linearlayout.setOrientation(LinearLayout.VERTICAL);
    }
  }


回答2:

In onCreate() put the following code:

int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
   // Landscape
   linearlayout.setOrientation(LinearLayout.HORIZONTAL); 
}
else {
   // Portrait  
    linearlayout.setOrientation(LinearLayout.VERTICAL); 
}