Android Shape Drawable 静态使用和动态使用(圆角,渐变实现)

来源:互联网 发布:json 解析工具 代码 编辑:程序博客网 时间:2024/06/05 13:12
Android Shape使用场景:

1. 圆角实现

2. 实现有边框,有填充的背景

3. 实现一个渐变的颜色

一般情况上面三种情况我们会选择android的shape,下面分别介绍shape的静态使用和动态使用

1. shape的静态使用

在drawable中创建一个xml文件,在布局文件中直接引用这个xml文件即可

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" >    <!-- 宽度和高度 -->    <size        android:width="50dp"        android:height="50dp"/>    <!-- 圆角 -->    <corners        android:radius="10dp"/><!-- 设置圆角半径,可以分别设置4个角 -->        <!-- 渐变,这个设置之后一般就不要设置solid填充色了 -->    <gradient        android:startColor="@android:color/white"        android:centerColor="@android:color/black"        android:endColor="@android:color/black"        android:useLevel="true"        android:angle="45"        android:type="radial"        android:centerX="0"        android:centerY="0"        android:gradientRadius="90"/>        <!-- 间隔 -->    <padding        android:left="5dp"        android:top="5dp"        android:right="5dp"        android:bottom="5dp"/>        <!-- 填充 -->    <solid        android:color="@android:color/white"/><!-- 填充的颜色 -->        <!-- 描边 -->    <stroke        android:width="1dp" <!-- 边框宽度 -->        android:color="@android:color/black"        android:dashWidth="1dp"        android:dashGap="2dp"/>    </shape>

 

2. 动态创建shape drawable并使用

View view = null;    // 这个view是你需要设置背景的viewint strokeWidth = 1;     // 1dp 边框宽度int roundRadius = 5;     // 5dp 圆角半径int strokeColor = Color.parseColor("#FFFF0000");//边框颜色int fillColor = Color.parseColor("#FF00FF00"); //内部填充颜色GradientDrawable gd = new GradientDrawable();//创建drawablegd.setColor(fillColor);gd.setCornerRadius(roundRadius);gd.setStroke(strokeWidth, strokeColor);view.setBackgroundDrawable(gd);        // 创建渐变的shape drawableint colors[] = { 0xff255779 , 0xff3e7492, 0xffa6c0cd };//分别为开始颜色,中间夜色,结束颜色GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);view.setBackgroundDrawable(gd);

3. 动态改变shape drawable的熟悉

既然shape drawable都能动态创建,那么肯定能过动态修改,我们可以通过先获取view上设置的background drawable

如果是GradientDrawable则强制转换为GradientDrawable,这个时候就可以修改里面的属性,像动态创建时一样设置,设置好之后重新设置给view.

GradientDrawable drawable =(GradientDrawable)view.getBackground();drawable.setColor(fillColor); // 设置填充色   drawable.gd.setStroke(strokeWidth, strokeColor); // 设置边框宽度和颜色gd.setColors(colors);    // 设置渐变颜色数组

 

0 0