在Android中以编程方式设置FrameLayout的前景色

12

我想以编程方式设置FrameLayout的前景色(而不是在XML属性中)。 我有RGB颜色代码。

我如何将颜色转换为可绘制对象:

frm.setForeground(Drawable);
2个回答

22

您可以从颜色创建Drawable

final int color = 0xFFFF0000;
final Drawable drawable = new ColorDrawable(color);

1
对于透明的组件,只需使用.setForeground(null)。 - Hamidreza Sadegh
1
从资源中获取颜色的代码为 new ColorDrawable(context.getResources().getColor(color)) - Zon

4
使用ContextCompat从颜色创建Drawable
int color = R.color.black_trans_60;
frm.setForeground(new ColorDrawable(ContextCompat.getColor(mContext, color)));

请使用ContextCompat代替直接颜色,因为新的API ColorDrawable需要ColorDrawable(@ColorInt int color)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接