Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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); 
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top