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

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>

代码文件结构:



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




竖屏:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值