如何以编程方式更改Shape纯色? [重复]

问题描述 投票:1回答:4

这个问题在这里已有答案:

如何以编程方式更改<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
    }
}
android
4个回答
0
投票

试试这个

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

0
投票

试试这个:-

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

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

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));
     }
 });

0
投票

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

GradientDrawable shape = (GradientDrawable) icon.getDrawable();
shape.setColor(Color.BLACK);
© www.soinside.com 2019 - 2024. All rights reserved.