如何以编程方式更改Shape纯色?

时间:2017-07-24 11:58:17

标签: android

如何以编程方式更改<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
    }
}

4 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分: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));
     }
 });

答案 2 :(得分:0)

试试这个: -

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

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

答案 3 :(得分:0)

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

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