用JAVA而不是XML中的设备方向调整布局方向



我想知道如何在JAVA中根据设备方向更改LinearLayout方向,我找到了如何通过XML方式与布局和布局陆地进行更改,但我没有找到如何通过JAVA方式进行更改。

非常感谢。

看到这里,它描述了如何在java 中检测方向更改然后更改方向

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

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

在onCreate((中放入以下代码:

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

最新更新