簡體   English   中英

(editText.getBackground == Drawable)總是返回false,為什么? 為了保持一致,它必須返回true,怎么做?

[英](editText.getBackground == Drawable) always returns false, why?. To be consistent it must return true, how?

我正在擰一個Android應用。 它包含一些EditText字段。 我還為他們編寫了自定義背景。

自定義背景位於res / drawable / bordered_edttext.xml

<?xml version="1.0" encoding="UTF-8" ?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="#ffffff" /> 
  <stroke android:width="1dp" android:color="@android:color/black" />   
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" /> 
</shape>

EditText引用它

    <EditText
        android:id="@+id/et_period"
        ...
        android:background="@drawable/bordered_edttext"
        ...
        />

然后在活動

   Drawable editText_background;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
      ...
      ...
      editText_background = getResources().getDrawable(R.drawable.bordered_edttext);
      boolean isbackground =  (et_period.getBackground() == editText_background);
      Toast.makeText(getApplicationContext(), "The background status is " + isbackground, 
           Toast.LENGTH_LONG).show();

   }

烤面包的結果始終是:“背景狀態為false ”。 一定是真的。

這是錯誤的,因為即使“圖像”相同,它也是2個不同的對象。 第一個是您的Edittext創建的對象,第二個是您從資源中繪制的對象。

如果要比較2個可繪制對象,則應使用.equals

嘗試這個:

et_period.getBackground().getConstantState()
        .equals(editText_background.getConstantState());

只需檢查Bellow Code Drawble無法與==兼容,就必須使用equals方法

    editText_background = getResources().getDrawable(R.drawable.shape);
    // boolean isbackground = (getConstantState()
    // .equals(editText_background.getConstantState()););
    Toast.makeText(
            getApplicationContext(),
            "The background status is "
                    + tv.getBackground().getConstantState()
                            .equals(editText_background.getConstantState()),
            Toast.LENGTH_LONG).show();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM