Android XML中的应用场景

1.简单图形使用图片文件的缺点

实际开发中,我们会遇到很多需要用到简单图形的地方,比如下面这个:
![图片型按钮Selector][101]
这个时候如果找美工要图片的话,虽然不用自己动手,但是有以下缺点
1.会增大APK体积:图片资源文件过多,比如实现上图的效果,至少需要5*2=10张图片(普通状态 +选中状态),如果根据不同分辨率配图的话,那文件数就更多了
2.修改麻烦:一点点小修改可能美工都需要全部重做
3.消耗性能:载入Bitmap应该会比XML文件更耗性能(待验证)

2.<shape>的层叠应用

那么如何是好呢,在recdrawable文件夹中新建文件rbtn_color_blue.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
    //当drawable状态为checked时显示的图形
    <item android:state_checked="true">
        <layer-list>//表示使用图形层级
            //第一层(底部蓝色)
            <item>                
                <shape android:shape="oval">//绘制图形,oval=圆形
                    <solid android:color="@android:color/holo_blue_light" />//载入系统holo主题的浅蓝色
                    <size android:width="20dp" android:height="20dp" />//图形的高宽
                </shape>
            </item>
            //第二层(面层白色),并向内偏移2dp
            <item android:bottom="2dp" android:left="2dp" android:right="2sp" android:top="2dp">
                <shape android:shape="oval">//绘制图形,oval=圆形
                    <stroke android:width="2dp" android:color="@android:color/white" />//白色环形带,宽度2dp
                    <size android:width="20dp" android:height="20dp" />//图形的高宽
                </shape>
            </item>
        </layer-list>
    </item>

    //当drawable状态为非checked时显示的图形
    <item android:state_checked="false">
        <layer-list>
            <item>
                <shape android:shape="oval">
                    <solid android:color="@android:color/holo_blue_light" />
                    <size android:width="20dp" android:height="20dp" />
                </shape>
            </item>
        </layer-list>
    </item>
</selector>

实际效果(Drawable的checked状态非checked状态):
![Drawable的checked状态][103]
![Drawable的非checked状态][102]

最终的效果是:
![<shape的实际效果>][104]
明显逼格高点,修改起来又容易对不对!
[101]:http://upload-images.jianshu.io/upload_images/1498308-cb9a79727466e60b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
[102]:http://upload-images.jianshu.io/upload_images/1498308-ba11520d4cd2f0dc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
[103]:http://upload-images.jianshu.io/upload_images/1498308-aceb6caac6beb86c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
[104]:http://upload-images.jianshu.io/upload_images/1498308-2b0d7bc5efaa54d9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240

    原文作者:彼时芒种
    原文地址: https://www.jianshu.com/p/30a85a26466f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞