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:

[html] view plain copy
 http://www.woaipu.com/shops/zuzhuan/61406
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <TextView  
  7.         android:layout_width="200dp"  
  8.         android:layout_height="150dp"  
  9.         android:layout_centerInParent="true"  
  10.         android:background="@android:color/holo_red_light"  
  11.         android:gravity="center"  
  12.         android:text="横屏" />  
  13.   
  14. </RelativeLayout>  



res/layout-port/activity_main.xml:

[html] view plain copy
 http://www.woaipu.com/shops/zuzhuan/61406
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6.     <TextView  
  7.         android:layout_width="133dp"  
  8.         android:layout_height="100dp"  
  9.         android:layout_centerInParent="true"  
  10.         android:background="@android:color/holo_red_light"  
  11.         android:gravity="center"  
  12.         android:text="竖屏" />  
  13.   
  14. </RelativeLayout>  

代码文件结构:

 http://www.woaipu.com/shops/zuzhuan/61406

代码在横竖屏切换时候的运行结果:
横屏:

http://www.woaipu.com/shops/zuzhuan/61406

原文地址:https://www.cnblogs.com/sy646et/p/7194107.html