在使用shape的同時,用代碼修改shape的顏色屬性

Android裏面經常會使用shape來定製一些View的背景

可以修改View的背景顏色,形狀等屬性


一般情況下,shape都是在xml文件裏面寫死了,今天遇到一個需求,View的形狀是圓角的,但是顏色是在代碼裏面設置的

最開始的思路是先在代碼裏給View設置顏色,再在shape裏面設置solid屬性爲透明色

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"/>
    
    <solid
        android:color="#00000000"/>

</shape>

View.setBackgroundColor(color);
View.setBackgroundDrawable(R.drawable.shape);

很遺憾,不能實現我想要的需求,每設置一次Background,Background就會就會被替換掉


最後上網Google了下,找到解決方案了http://stackoverflow.com/questions/16775891/how-to-change-solid-color-from-the-code

GradientDrawable myGrad = (GradientDrawable)view.getBackground();
myGrad.setColor(color);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章