【发布时间】:2012-02-11 17:13:12
【问题描述】:
在我的测试中,我想确保 View(不是 ImageView)具有特定的背景颜色。我怎样才能通过与相关视图交互来直接做到这一点?
此视图的背景不是 Drawable。它要么在 XML 中设置,要么使用 view.setBackgroundColor(...) 设置。
【问题讨论】:
标签: android testing background-color
在我的测试中,我想确保 View(不是 ImageView)具有特定的背景颜色。我怎样才能通过与相关视图交互来直接做到这一点?
此视图的背景不是 Drawable。它要么在 XML 中设置,要么使用 view.setBackgroundColor(...) 设置。
【问题讨论】:
标签: android testing background-color
这将需要您进行一些重构,但您可以使用 setBackgroundDrawable() 并传入 ColorDrawable 的实例,而不是使用 setBackgroundColor()。它真的不再像你以前那样工作了,ColorDrawable 允许你设置它的颜色,并在你执行测试时得到它。所有 View 对象都响应 getBackground() 方法,该方法返回该实例的 Drawable。
这应该对你有用,而且它并不会真正增加任何开销,因为即使你调用 setBackgroundColor,Android 也需要为你创建一个 Drawable
【讨论】:
Drawable drawable = view.getBackground(); 如何从可绘制对象中恢复颜色(或资源 ID)?我看到我可以恢复不透明度,但我看不到如何恢复颜色,我认为恢复资源 ID 是不可能的。
ColorDrawable 有一个 getColor() 方法,该方法返回一个表示其颜色的 int 值。当您创建 ColorDrawable 对象时,您将调用 setColor() 来设置背景颜色。现在您可以比较两个 int 颜色值来查看它们是否相等。您需要将其转换为 ColorDrawable,而不是 Drawable 接口
ColorDrawable drawable = (ColorDrawable)view.getBackground();
【讨论】:
Exception:java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
您可以使用它来获取 textview 的背景颜色..
yourTextView.getBackgroundResource(R.color.white);
其中 color.xml 在 res/values 文件夹中定义为
<color name="white">#ffffffff</color>
【讨论】: