我应该如何在android studio中获得颜色并比较它们?

bmp9r5qi  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(357)

在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
v7pvogib

v7pvogib1#

如果您将直接色码用于只有以下单色的背景:

<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
}

相关问题