2
工作,我有一個背景繪製這樣的:上GradientDrawable設置顏色不是從片段
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:bottom="80dp"
android:id="@+id/card_background">
<shape>
<solid android:color="@color/x_card_color_pink"
android:height="100dp"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
</shape>
</item>
<item android:top="120dp">
<shape>
<solid android:color="@color/white"
android:height="100dp"/>
<corners
android:bottomLeftRadius="10dp"
android:bottomRightRadius="10dp"/>
</shape>
</item>
</layer-list>
我想改變的card_background
顏色。當我從活動onCreate
設置新的顏色它的工作原理:
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(this, R.drawable.card_background);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.card_background);
gradientDrawable.setColor(0xFFEBC51B); //Successfully set to yellow from activity
但是如果嘗試從也顯示背景片段設置它,我不能讓它改變。我希望能夠做到這一點的clickHandler事件以後,但現在我使用的片段onCreate
相同的代碼:
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getActivity(), R.drawable.card_background);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.card_background);
gradientDrawable.setColor(0xFF5ABC63); //Fail to set to green from fragment
即時通訊思想,因爲我顯示了在同一時間段,因爲我更新我必須刷新它或什麼?我嘗試了方法invalidateSelf
,但沒有效果。
關於如何從片段更改背景顏色的任何想法?
通過'layerDrawble = layout.getBackground()'初始化'layerDrawable'也行得通,而且更簡單。 –