1,介绍:
-
在Android开发中,我们可以使用shape定义各种各样的形状,也可以定义一些图片资源。相对于传统图片来说,使用shape可以减少资源占用,减少安装包大小,还能够很好地适配不同尺寸的手机。
2,基本属性
-
Shape可以定义控件的一些展示效果,例如圆角,渐变,填充,描边,大小,边距;shape子标签就可以实现这些效果,
-
shape子标签有下面几个属性:corners,gradient,padding,size,solid,stroke:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape=["rectangle" | "oval" | "line" | "ring"] > // 定义形状
<corners //圆角属性
android:radius="integer"
android:topLeftRadius="integer"
android:topRightRadius="integer"
android:bottomLeftRadius="integer"
android:bottomRightRadius="integer" />
<gradient //渐变属性
android:angle="integer"
android:centerX="integer"
android:centerY="integer"
android:centerColor="integer"
android:endColor="color"
android:gradientRadius="integer"
android:startColor="color"
android:type=["linear" | "radial" | "sweep"]
android:useLevel=["true" | "false"] />
<padding //边距属性
android:left="integer"
android:top="integer"
android:right="integer"
android:bottom="integer" />
<size //大小属性
android:width="integer"
android:height="integer" />
<solid //填充属性
android:color="color" />
<stroke //描边属性
android:width="integer"
android:color="color"
android:dashWidth="integer"
android:dashGap="integer" />
</shape>
3,怎么使用
【1】
首先在res/drawable文件夹下,新建一个文件,命名为:shape_radius.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<corners android:radius="20dip"/>
<solid android:color="#ff00ff"/>
</shape>
【2】
在定义好shape文件后,下一步就是将其添加到控件中,添加到控件中,一般是使用设置background属性,将其为控件背景,下面,我们将其设置为MainActivity对应的布局中(activity_main.xml),将其设为TextView的背景,看显示出来 是什么样子的。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.harvic.tryshape.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="50dip"
android:text="@string/hello_world"
android:background="@drawable/shape_radius"/>
</RelativeLayout>
【3】实现效果
![](https://img-blog.csdnimg.cn/2019112512061276.png)
Android XML资源文件相关:
https://blog.csdn.net/cricket_7/category_9540223.html