zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案详解手机开发

AndroidXML解决方案手机开发 详解 设置 不同
2023-06-13 09:20:06 时间
Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案

在一些应用中,涉及到横竖屏切换,View要切换成不同大小比例尺寸。为解决这种开发场景,有多种解决方案,比如可以重写View,实现横竖切换在onMesure或者此类View的回调方法里面重新测量重新绘制View的尺寸大小。还有可以在onConfigurationChanged里面根据当前的横竖屏切换情况重写设置View的长宽比例等等。
现在给出一种比较简单且较为灵活的处理方法:通过写两套xml布局,实现在不同横竖屏切换状态下的不同大小比例尺寸。这种方案的关键做法是在res里面放置两个layout,分别叫做layout-land和layout-port。layout-land横屏时候将被加载,layout-port竖屏时候加载。只需要写两个同名的布局文件,但是要分别放在res/layout-land和layout-port文件目录下。这样在横竖屏切换时候Android系统就会自动根据当前横竖屏情况加载相应的布局。
给出一个例子,本例只有一个activity_main.xml,需要在不同横竖屏切换时候加载不同相应的布局。那么就分别写两个不同activity_main.xml但是同名的布局文件。
res/layout-land/activity_main.xml:

 ?xml version= 1.0  encoding= utf-8 ?  

 RelativeLayout xmlns:android= http://schemas.android.com/apk/res/android  

 android:layout_width= match_parent  

 android:layout_height= match_parent  

 

  TextView 

 android:layout_width= 200dp  

 android:layout_height= 150dp  

 android:layout_centerInParent= true  

 android:background= @android:color/holo_red_light  

 android:gravity= center  

 android:text= 横屏  /  

 

 /RelativeLayout 

res/layout-port/activity_main.xml:

 ?xml version= 1.0  encoding= utf-8 ?  

 RelativeLayout xmlns:android= http://schemas.android.com/apk/res/android  

 android:layout_width= match_parent  

 android:layout_height= match_parent  

 

  TextView 

 android:layout_width= 133dp  

 android:layout_height= 100dp  

 android:layout_centerInParent= true  

 android:background= @android:color/holo_red_light  

 android:gravity= center  

 android:text= 竖屏  /  

 

 /RelativeLayout 

代码文件结构:

Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案详解手机开发

代码在横竖屏切换时候的运行结果:
横屏:
Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案详解手机开发

竖屏:
Android横竖屏切换View设置不同尺寸或等比例缩放的XML解决方案详解手机开发

3131.html

服务器部署程序员系统优化网站设置运维