我编辑,使问题更简单,希望有助于实现一个准确的答案。
说我有以下椭圆
形状:
< XML版本=1.0编码=UTF-8&GT?;
<形状的xmlns:机器人=http://schemas.android.com/apk/res/android机器人:形状=椭圆形>
[固体安卓角=270
机器人:颜色=#FFFF0000/>
<行程机器人:宽=3DP
机器人:颜色=#FFAA0055/>
< /形状>
我如何设置颜色编程方式,从活动类中?
解决方案在绘制一个椭圆,是一个ImageView的背景
获得绘制对象
从的ImageView
使用的getBackground()
:
可绘制背景= imageView.getBackground();
核对秋后算账:
如果(背景的instanceof ShapeDrawable){
//投地'ShapeDrawable
ShapeDrawable shapeDrawable =(ShapeDrawable)背景;
。shapeDrawable.getPaint()setColor(getResources()的getColor(R.color.colorToSet));
}否则,如果(背景的instanceof GradientDrawable){
//投地'GradientDrawable
GradientDrawable gradientDrawable =(GradientDrawable)背景;
gradientDrawable.setColor(getResources()的getColor(R.color.colorToSet));
}
紧凑型:
可绘制背景= imageView.getBackground();
如果(背景的instanceof ShapeDrawable){
((ShapeDrawable)背景).getPaint()setColor(getResources()的getColor(R.color.colorToSet)。)。
}否则,如果(背景的instanceof GradientDrawable){
((GradientDrawable)背景).setColor(getResources()的getColor(R.color.colorToSet)。);
}
请注意,不要求空检查。
I am editing to make the question simpler, hoping that helps towards an accurate answer.
Say I have the following oval
shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:angle="270"
android:color="#FFFF0000"/>
<stroke android:width="3dp"
android:color="#FFAA0055"/>
</shape>
How do I set the color programmatically, from within an activity class?
解决方案The drawable is an oval and is the background of an ImageView
Get the Drawable
from imageView
using getBackground()
:
Drawable background = imageView.getBackground();
Check against usual suspects:
if (background instanceof ShapeDrawable) {
// cast to 'ShapeDrawable'
ShapeDrawable shapeDrawable = (ShapeDrawable)background;
shapeDrawable.getPaint().setColor(getResources().getColor(R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
// cast to 'GradientDrawable'
GradientDrawable gradientDrawable = (GradientDrawable)background;
gradientDrawable.setColor(getResources().getColor(R.color.colorToSet));
}
Compact version:
Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
((ShapeDrawable)background).getPaint().setColor(getResources().getColor(R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
((GradientDrawable)background).setColor(getResources().getColor(R.color.colorToSet));
}
Note that null-checking is not required.