如何通过编程更改形状的实心颜色?

5

如何在程序中更改<solid android:color= />的值?

我定义了一个自定义形状元素:

my_item.xml:

<shape android:shape="oval">
    <solid android:color="#FFFF0000"/>
</shape>

并在另一个布局中重复使用它: grid_view.xml:

<LinearLayout>
    <ImageView ... android:src="@drawable/my_item"
                   android:id="@+id/myitemid" />
</LinearLayout>

以下方法无法正常工作:
public class ShapeItemAdapter extends BaseAdapter {

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
          view = inflter.inflate(R.layout.grid_view, null);
          ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
          shape.setBackgroundColor(0xBCCACA); //does not work
    }
}

你在提问之前有没有查看过这个链接 - Piyush
4个回答

5

在这里提供的所有答案都不正确。重要的是:在形状上使用 getDrawable() 而不是 getBackground()

GradientDrawable shape = (GradientDrawable) icon.getDrawable();
shape.setColor(Color.BLACK);

2

试试这个:

从资源中获取您的可绘制对象并更改形状颜色。然后,您可以将其设置为图像视图的背景。

      GradientDrawable drawable = (GradientDrawable) mContext.getResources()
            .getDrawable(R.drawable.todo_list_circle);
    drawable.mutate();
    drawable.setColor(mColor);

0

试试这个

ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
GradientDrawable bgShape = (GradientDrawable)shape.getBackground();
bgShape.setColor(Color.BLACK);

形状是 ShapeDrawable... - membersound

0
获取 ShapeDrawable 并设置颜色:
ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground();
shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color));

您可以等待布局绘制完成后再执行:

 ViewTreeObserver to = shape.getViewTreeObserver();
 to.addOnGlobalLayoutListener (new OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
         layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
         ImageView shape = (ImageView) view.findViewById(R.id.myitemid);
         ShapeDrawable shapeDrawable = (ShapeDrawable) shape.getBackground();
         shapeDrawable.getPaint().setColor(ContextCompat.getColor(context,R.color.my_color));
     }
 });

shape.getBackground() 返回 null。为什么我没有背景? - membersound
我更新了我的回答 @membersound - Fori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接