如何解决我应该如何获取颜色并在 android studio 中比较它们?
在 Drawable 文件夹中我有 white.xml
.......
在 mainactivity.xml 我有 textview
android:id="@+id/text1"
android:background="@drawable/white" />```
//secound textview same as above
**In mainActivity i want to get background Color and to compare them but its not working**
``` public void getColor(View view) {
Drawable color1 = findViewById(R.id.text1).getBackground();
Drawable color2 = findViewById(R.id.text2).getBackground();
if(color1 == color2)
enter code here
//its also not working with .equal function
}```
// how should i compare background color
解决方法
如果您对背景使用直接颜色代码,只有这样的单一颜色:
<TextView
android:id="@+id/textviewWithColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000" <!--A direct color code instead of a drawable-->
android:textSize="16sp"/>
您可以通过以下方式获取整数颜色代码:
ColorDrawable background = (ColorDrawable) textviewWithColor.getBackground();
int colorCode = background.getColor();
在你的情况下,你可以这样做:
int color1 = (ColorDrawable) findViewById(R.id.text1).getBackground().getColor();
int color2= (ColorDrawable) findViewById(R.id.text2).getBackground().getColor();
if(color1 == color2){
//The color matches,do something
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。