[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