如何在ImageView中使用ColorDrawable?

use*_*114 17 android

我有一个ImageView定义的布局,如:

<ImageView
  android:layout_width="45dip"
  android:layout_height="45dip"
  android:scaleType="fitXY" />
Run Code Online (Sandbox Code Playgroud)

现在我只想将imageview设置为静态颜色,如红色或绿色.我尝试着:

ColorDrawable cd = new ColorDrawable("FF0000");
cd.setAlpha(255);
ImageView iv = ...;
iv.setImageDrawable(cd);
Run Code Online (Sandbox Code Playgroud)

imageview只是空的,没有颜色.45dip空间正在用尽.我需要做什么才能渲染颜色?

谢谢

Mar*_*k B 28

查看ColorDrawable的构造函数,我没有看到像您的示例中那样采用字符串的版本.我看到一个采用int.试试这个:

ColorDrawable cd = new ColorDrawable(0xffff0000);
Run Code Online (Sandbox Code Playgroud)

注意我使用了8个十六进制数字,而不是像你的例子中的6个.这也设置了alpha值.

编辑:回顾一下我自己做过的类似的代码,我总是使用setBackgroundDrawable()而不是setImageDrawable()来初始化一个纯色的ImageView.不确定这是否会产生影响.

  • 如果你想以编程方式使用带颜色的选择器(不是drawable)你可以使用:`ColorDrawable cd = new ColorDrawable(Color.parseColor("#FFEDCACA"));` (6认同)