自定义控件Android专题安卓UI

Android Drawable之GradientDrawabl

2019-02-28  本文已影响196人  itfitness

目录

目录

GradientDrawable是什么

GradientDrawable在Android中便是shape标签的代码实现,利用GradientDrawable也可以创建出各种形状。

GradientDrawable使用方法

1. 获取控件的shape并进行动态修改:
既然GradientDrawable是shape的动态实现,那么他就可以通过动态的获取控件的shape获取实例并进行修改,例如动态改变一个矩形shape的颜色并添加圆角:


布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.itfitness.drawabledemo.MainActivity">
    <Button
        android:text="Change"
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <View
        android:id="@+id/view"
        android:background="@drawable/shape_rect"
        android:layout_width="300dp"
        android:layout_height="300dp" />
</LinearLayout>

shape_rect.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@color/colorAccent"/>
</shape>

java代码中进行动态修改

GradientDrawable background = (GradientDrawable) view.getBackground();//获取对应的shape实例
background.setColor(Color.GREEN);//设置为绿色
background.setCornerRadius(20);//设置圆角
view.setBackgroundDrawable(background);

2. 通过代码动态创建:

//什么都不指定默认为矩形
GradientDrawable background = new GradientDrawable();
background.setColor(Color.GREEN);
view.setBackgroundDrawable(background);

如果想要设置形状的话可以通过setShape(int shape) 方法来进行设置,这里一共可以设置四种形状:
GradientDrawable background = new GradientDrawable();
background.setColor(Color.GREEN);
background.setShape(GradientDrawable.OVAL);
view.setBackgroundDrawable(background);

如果想让效果更加丰富一些添加描边或者颜色渐变:

GradientDrawable background = new GradientDrawable();
background.setShape(GradientDrawable.OVAL);
background.setStroke(10,Color.RED);//设置宽度为10px的红色描边
background.setGradientType(GradientDrawable.LINEAR_GRADIENT);//设置线性渐变,除此之外还有:GradientDrawable.SWEEP_GRADIENT(扫描式渐变),GradientDrawable.RADIAL_GRADIENT(圆形渐变)
background.setColors(new int[]{Color.RED,Color.BLUE});//增加渐变效果需要使用setColors方法来设置颜色(中间可以增加多个颜色值)
view.setBackgroundDrawable(background);
上一篇 下一篇

猜你喜欢

热点阅读