获取视图的背景颜色(十六进制)

4

我希望能够以十六进制格式获取视图的背景色。

例如,考虑int getViewBackgroundColor(View view),我的期望返回值是0Xff256e78

我应该如何做到这一点?

谢谢。

4个回答

7
LinearLayout layout = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) layout.getBackground();
int colorId = viewColor.getColor();

在获取颜色的整数类型后,现在你需要将其转换为十六进制:

String hexColor = String.format("#%06X", (0xFFFFFF & colorId));

希望这能帮到您...

谢谢,它可以工作,但它是字符串,要将其转换为长整型 -> Long.parseLong(hexColorString, 16) - alizeyn

0
以下代码将获取一个视图的背景颜色并将其转换为颜色的 int 表示形式。
ColorDrawable buttonColor = (ColorDrawable) myView.getBackground();
int colorId = buttonColor.getColor();

0

这个答案与其他答案没有区别,但它是最短的:

((ColorDrawable)yourView.getBackground()).getColor()

0

这是Kotlin语言的答案:

var view: View = findViewById(R.id.bg_view_id)
var draw: ColorDrawable = view.background as ColorDrawable
var color_id = draw.getColor()

Log.i("UYARI-INFO: ", Integer.toHexString(color_id))

在Logcat中输出将为:

I/UYARI-INFO:: ffffd8af

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