سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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); 
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top