[Android]动态改变shape背景颜色


shape在写奇奇怪怪界面的时候经常会使用到,比如圆角布局。

但是有时候我们需要改变shape的背景颜色,xml写死了,直接对布局进行view.setBackgroundColor会替换掉原来的shape样式,
这时候就需要动态改变shape背景颜色。

布局文件: 背景设置为shape文件

<LinearLayout
android:layout_width="300dp"
android:layout_height="200dp"
android:background="@drawable/shape_rand" 
android:id="@+id/llview"/>

shape文件:
shape_rand.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--rectangle矩形-->
    <!--圆角-->
    <corners 
        android:radius="5dp"/>
    <!--大小-->
    <size android:width="1dp" android:height="1dp"></size>
    <!--描边-->
    <solid android:color="#ffff0000"></solid>

</shape>

这时候已经出现一个圆角红色长方形
之后改变shape背景颜色

//获取llview当前背景,返回一个Drawable
GradientDrawable myShape = (GradientDrawable)findViewById(R.id.llview).getBackground();
myShape.setColor(0xff00ff00);//绿色

已经变成绿色了!圆角还在!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM