我试图创建一个带有文字和图像的圆形按钮。我想在我的活动中以编程方式添加它,并同时更改背景颜色。
以下工作正常,但没有图像。 button_round.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false"
android:id="@+id/button_round_oval">
<shape android:shape="oval"
android:id="@+id/button_round_oval_shape">
<solid android:color="#52a0e8"/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#3280c8"/>
</shape>
</item>
</selector>
活动:
...
Button b = new Button(this);
...
b.setText(myText);
b.setBackgroundResource(R.drawable.button_round); //the drawable above
GradientDrawable bgShape = (GradientDrawable)b.getBackground().getCurrent();
bgShape.setColor(Color.parseColor("#0000FF"));
...
我搜索了一个解决方案,但无法使其正常工作(例如:Programmatically change color of shape in layer list)。
这是我到目前为止所尝试的内容:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false"
android:id="@+id/button_round_oval">
<layer-list
android:id="@+id/button_round_oval_layer">
<item
android:id="@+id/button_round_oval_item">
<shape
android:shape="oval"
android:id="@+id/button_round_oval_shape">
<solid android:color="#52a0e8"/>
</shape>
</item>
<item>
<bitmap
android:gravity="center"
android:src="@drawable/stars_one" />
</item>
</layer-list>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#3280c8"/>
</shape>
</item>
</selector>
在我尝试的活动中,例如:
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getApplicationContext(), R.drawable.button_round);
GradientDrawable bgShape = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.button_round_oval_item);
bgShape.setColor(Color.parseColor("#0000FF"));
但在这种情况下,我收到了错误消息:
android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.LayerDrawable
第二个问题是(当这个工作时),如何改变state_pressed的背景颜色。
提前致谢!