Search code examples
androidandroid-layoutandroid-orientationdevice-orientation

Adjusting layout Orientation with the device orientation in JAVA not XML


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.


Solution

  • 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);
        }
      }