【问题标题】:How to change Shape solid color programmatically? [duplicate]如何以编程方式更改形状纯色? [复制]
【发布时间】:2017-07-24 11:58:16
【问题描述】:

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

【问题讨论】:

  • 提问前你检查过this吗?

标签: android


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这个:-

    从资源中获取您的drawable并更改形状颜色。然后您可以设置为图像视图的背景。

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

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

      • 形状是ShapeDrawable...
      【解决方案4】:

      获取 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
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多