如果你刚好做了一个平板项目,然后项目经理说你需要实现横竖屏的切换功能,但你又不想横竖屏切换加载不同的布局(可以新建layout和layout-port,系统
会自动判断你的屏幕状态,加载对应的布局),因为这样需要重新初始化activity或者fragment,用户体验不好,比不上直接横竖屏切换的,我参考 动态设置权重
的方法,前提是你的布局采用权重的方式进行布局的layout_weight,如下:
所以我的方法是,当横竖屏切换的时候,不需要加载新的布局view文件,动态在onConfigurationChanged修改布局的权重来实现,如下步骤:
1.首先设置:AndroidManifest.xml中的activity中的属性:android:configChanges="keyboardHidden|orientation|screenSize"
防止横竖屏切换时,避免重新加载,以便能在onConfigurationChanged进行监听
2.重写activity或者fragment中的onConfigurationChanged方法。
会自动判断你的屏幕状态,加载对应的布局),因为这样需要重新初始化activity或者fragment,用户体验不好,比不上直接横竖屏切换的,我参考 动态设置权重
的方法,前提是你的布局采用权重的方式进行布局的layout_weight,如下:
<LinearLayout
android:id="@+id/toplayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal" >
所以我的方法是,当横竖屏切换的时候,不需要加载新的布局view文件,动态在onConfigurationChanged修改布局的权重来实现,如下步骤:
1.首先设置:AndroidManifest.xml中的activity中的属性:android:configChanges="keyboardHidden|orientation|screenSize"
防止横竖屏切换时,避免重新加载,以便能在onConfigurationChanged进行监听
2.重写activity或者fragment中的onConfigurationChanged方法。
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//上下的布局权重调整
LinearLayout toplayout = (LinearLayout) findViewById(R.id.toplayout);
LinearLayout.LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 2.0f);
toplayout.setLayoutParams(lp);
LinearLayout tradespace_layout = (LinearLayout) findViewById(R.id.tradespace_layout);
LinearLayout.LayoutParams lp3 = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 2.8f);
tradespace_layout.setLayoutParams(lp3);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//上下的布局权重调整
LinearLayout toplayout = (LinearLayout) findViewById(R.id.toplayout);
LinearLayout.LayoutParams lp = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 2.8f);
toplayout.setLayoutParams(lp);
LinearLayout tradespace_layout = (LinearLayout) findViewById(R.id.tradespace_layout);
LinearLayout.LayoutParams lp3 = new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 2.0f);
tradespace_layout.setLayoutParams(lp3);
}
}
参考的博客内容如下,感谢这位博主:
在平板项目中,由于一开始针对的横屏的开发界面,布局上都是使用权重,但后期需求改了,要求要竖屏,为了避免横竖屏加载新的布局文件,想着如果能动态调整布局的权重就好了,找到如下的文章:
比如你在一个布局文件中,LinearLayout节点中动态的添加子控件的时候,因为不知道要添加控件的数量,那么我们就需要设置权重,weight,所以我们要动态的给控件设置权重,下面就给出一个方法设置权重。
动态的给控件设置权重,前提是:此控件必须是在LinearLayout标签中,
例如:
Ll_layout.xml
在代码中设置TextView的权重,weight
注意点:
如果在给空间设置权重的时候,如果布局中设置的方向是horizontal,那么就在LayoutParams(0,heignt,weight)
如果在给空间设置权重的时候,如果布局中设置的方向是vertical,那么就在LayoutParams(width,0,weight)
也可以不设置为0,有的时候会出现和其他布局设置的权重不会对其,很难调试。
那里有不足的地方,请大家指出,互相讨论和学习。