如何更改imageview中设置的形状颜色

时间:2012-05-16 12:09:20

标签: android

现在问题始于设置形状的颜色。 我在drawable中创建了一个矩形形状,并将其设置为ImageView,如此

<LinearLayout 
        android:layout_width="0dp" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" 
        android:layout_weight="0.15" 
        android:layout_marginRight="10dp"
        android:gravity="center_vertical">
       <ImageView 
        android:id="@+id/iv_priority"
        android:src="@drawable/case_priority"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/>
</LinearLayout>

修改

我的case_priority.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <solid android:color="#009600" />
  <size android:width="30dp"
        android:height="30dp" />
</shape>

现在我需要改变这个形状的颜色。实际上这种颜色来自网络服务,我需要改变它。 所以我的问题是:我们如何以编程方式更改此形状的颜色。并将其设置为imageview。 我在stackoverflow中经历了一些例子,但我无法将其更改为图像视图。请帮助!!!! 提前谢谢。

修改

可能我在我的问题中并不清楚,所以只是提出质疑。实际上我有一个ImageView,我设置了一个实际上是drawable的源。默认情况下,它在我的代码中显示为绿色。现在Web服务返回此图像视图的颜色,需要相应地更改,因此我无法在运行时从xml更改它,所以我需要从java文件更改它。由于我使用的是形状和图像视图,因此.setBackground()在这里没什么用处。那么可能的解决方案是什么呢?感谢您的回答并抱歉给您带来不便。

6 个答案:

答案 0 :(得分:10)

Thanx所有答案。它帮助我回答。

在我的布局中,我更改了android:src="" to android:background="@drawable/case_priority" 在我的java文件中,我n =包含此代码: - &gt;

        Resources res = getResources();
        final Drawable drawable = res.getDrawable(R.drawable.case_priority);
        drawable.setColorFilter(Color.YELLOW, Mode.SRC_ATOP);
        ImageView img = (ImageView)findViewById(R.id.iv_priority);
        img.setBackgroundDrawable(drawable);

就是这样。希望有人。

答案 1 :(得分:3)

将此添加到图像视图

android:background="#152" // or some other color code

编辑1: 使用代码执行此操作

ImageView.setBackgroundColor(Color.parseColor("red")); // Or any color code like #000 , #987

编辑2:

ImageView Imgs = (ImageView) findViewById(R.id.iv_priority);

Imgs.setBackgroundColor(Color.parseColor("ColorCode"));

答案 2 :(得分:3)

看看这里

http://developer.android.com/guide/topics/graphics/2d-graphics.html#shape-drawable

如果您愿意,可以使用Shape来扩充XML,而不是在代码中创建inflate

答案 3 :(得分:2)

IimageView.setBackgroundColor( “#152”);

答案 4 :(得分:1)

所有解决方案都建议使用ImageView的背景。我认为这不是理想的解决方案。这个问题已经反映了一种直观的方法:将形状应用于src属性。然后,为了以编程方式更改形状的颜色,您将执行以下操作:

GradientDrawable drawable = (GradientDrawable) priorityImageView.getDrawable();
drawable.setColor(Color.RED);

鉴于形状的分配符合原始问题:

<ImageView 
    android:id="@+id/iv_priority"
    android:src="@drawable/case_priority"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/>

这也带来了一个优点,即您可以将ImageView的背景与其内容分开设置。

答案 5 :(得分:0)

作为Lars Blumberg's answer我也不想更改背景,所以我将以下代码应用于我的Image代码,因为我没有GradientDrawable:

Drawable drawable = imageView.getDrawable();
drawable.setColorFilter(Color.CYAN, PorterDuff.Mode.MULTIPLY);
相关问题