2010-03-30 81 views
14

我有一个ImageView的布局定义如下:如何将ColorDrawable与ImageView结合使用?

<ImageView 
    android:layout_width="45dip" 
    android:layout_height="45dip" 
    android:scaleType="fitXY" /> 

现在我只想设置ImageView的是一个静态的色彩,如红色或绿色。我试图:

ColorDrawable cd = new ColorDrawable("FF0000"); 
cd.setAlpha(255); 
ImageView iv = ...; 
iv.setImageDrawable(cd); 

imageview只是空的,虽然没有颜色。尽管45dip空间已经用完了。我需要做什么才能让颜色呈现?

感谢

回答

26

望着用于ColorDrawable我没有看到一个版本,在您的例子接受一个string类的构造函数。我看到一个采取整数。试试这个:

ColorDrawable cd = new ColorDrawable(0xffff0000); 

通知我在你的例子中使用8个十六进制数字,而不是6等。这也设置了alpha值。我回头看了一些我自己的代码,我做了类似的事情,我总是用setBackgroundDrawable()代替setImageDrawable()来用纯色初始化ImageView。不知道这是否会有所作为。

+0

感谢我提供的颜色诠释,我用Color.parseColor(),现在它的作品。 – user246114 2010-03-31 02:17:07

+5

如果你想通过编程方式使用带颜色的选择器(不可绘制),你可以使用:'ColorDrawable cd = new ColorDrawable(Color.parseColor(“#FFEDCACA”));' – Houcine 2013-04-03 14:58:53

+0

对于任何寻找如何将纯色设置为可绘制的(像我一样),使用imageView.setBackgroundColor()更容易 – 2013-07-31 18:18:06