android - 比较Android应用程序中布局的背景颜色

标签 android

我想制作一个 if 语句,在其中比较布局背景颜色的颜色,如下所示:

 RelativeLayout screen = (RelativeLayout) findViewById (R.id.screen);
 if(screen.getBackgroundColor() == "#FFFFFFFF"){
    //do something...
 }
 else{
   //do something else...
 }

我不知道如何获取背景颜色。我通过以下方式设置颜色: screen.setBackgroundColor(Color.parseColor("#000000"));

最佳答案

没有直接的 getBackgroundColor(),但如果您确实需要知道颜色值,则应该检索 View 的 Paint object并从中获取颜色:

Paint viewPaint = ((PaintDrawable) view.getBackground()).getPaint();
int colorARGB = viewPaint.getColor();

请注意,这也包含 alpha,因此在比较时要小心(或者如果您只需要比较 RGB,则去掉 alpha:

int colorRGB = colorARGB & 0x00ffffff;

这适用于所有 API 级别。

编辑

至于比较 - 一旦检索到颜色,您可以使用 Color.parseColor()并以通常的方式比较结果:

if( colorRGB == Color.parseColor("#ffffff") ) {
   // matches...
}

或与 ARGB 相同:

if( colorARGB == Color.parseColor("#ffffffff") ) {
   // matches...
}

如果您经常这样做(例如 in.list 适配器),我会解析一次并存储结果以供重用。

关于android - 比较Android应用程序中布局的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13194973/

相关文章:

android - 安装错误 : INSTALL_PARSE_FAILED_MANIFEST_MALFORMED code included

Android - 如何实现搜索功能并将结果返回到 ListView 中?

安卓 : Widget - Null pointer Exception when using setOnclickPendingIntent on the remoteviews?

java - 我从 Volley 响应 'Android way' 更新 textview 的方法是否正确?

android - 执行失败 ':app:transformClassesWithDexForDebug'-超出了GC开销限制

android - 如何将变量传递给broadCastReceiver

android - 有没有办法在 AndroidTestCase 中打开和关闭连接?

android - 样式 appcompat-v7 工具栏菜单背景

database - Android:数据库读取问题抛出异常

java - 服务 android 中的 android.os.deadobjectexception