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);//綠色
已經變成綠色了!圓角還在!