[英]Change colors of solid in drawable selector
我有以下可繪制對象:
<item android:state_pressed="true" android:text="texting .....">
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke android:width="@dimen/circleStrokeThickness" android:color="@color/earlGreen" />
<solid
android:color="@color/lightGrey"/>
<size
android:width="100dp"
android:height="100dp"/>
</shape>
</item>
<item android:state_pressed="false" android:text="texting .....">
<shape
xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke android:width="4dp" android:color="@color/earlGreen" />
<solid
android:color="@android:color/white"/>
<size
android:width="100dp"
android:height="100dp"/>
</shape>
</item>
但是,我需要一些類似的顏色,其中純色不同,但其余顏色相同。 有什么簡單的方法可以做到這一點,還是應該只定義一些xml文件? 我知道可以在運行時更改背景顏色,但是我看不到如何獲得特定狀態的顏色。
您可以為形狀項目<item android:id="@+id/shape_bacground"../>
定義ID,然后在運行時必須獲取視圖背景並將其轉換為LayerDrawable
並使用findDrawableByLayerId()
查找形狀並使用setColor()
設置顏色。 這是示例代碼:
可繪制的xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/float_button_shadow1">
</item>
<item
android:id="@+id/shape_bacground"
android:bottom="2dp"
android:left="1dp"
android:top="1dp"
android:right="1dp">
<shape android:shape="oval" >
<solid android:color="#1E88E5" />
</shape>
</item>
</layer-list>
變色
try {
LayerDrawable layer = (LayerDrawable) view.getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);// set new background color here
rippleColor = makePressColor();
} catch (Exception ex) {
// Without bacground
}
您可以通過編程來執行相同的操作,在其中可以通過運行函數並在參數中傳遞Color來在運行時更改任何顏色。
ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
sd1.getPaint().setColor(CommonUtilities.color);
sd1.getPaint().setStyle(Style.STROKE);
sd1.getPaint().setStrokeWidth(CommonUtilities.stroke);
sd1.setPadding(15, 10, 15, 10);
sd1.getPaint().setPathEffect(
new CornerPathEffect(CommonUtilities.corner));
ln_back.setBackgroundDrawable(sd1);
希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.