2016-01-21 126 views
1

我是剛接觸Android的編輯文本,右側有一個清除按鈕,工作正常,但我想清楚地顯示當用戶開始輸入時按鈕,但是當這個編輯文本爲空時,我不想顯示這個按鈕。編輯文本的我的xml是。如何在Android中編輯時在編輯文本中顯示清除按鈕

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/editText" 
    android:background="@android:color/transparent" 
    android:hint="Email" 
    android:layout_marginTop="12dp" 
    android:layout_weight="1" 
    android:layout_below="@+id/view_divider_top_email" 
    android:layout_alignLeft="@+id/view_divider_top_email" 
    android:layout_alignStart="@+id/view_divider_top_email" 
    android:layout_alignRight="@+id/view_divider_top_email" 
    android:layout_alignEnd="@+id/view_divider_top_email" 
    android:drawableRight="@android:drawable/ic_delete" //this line will put the cross button on right of edit text 
    /> 

我怎樣才能做到這一點

回答

3

EditTextaddTextChangeListener()嘗試。當用戶鍵入或從EditText中刪除某些內容時,它將被調用。

edt.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 

      // TODO Auto-generated method stub 
     } 

     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

      // TODO Auto-generated method stub 
     } 

     @Override 
     public void afterTextChanged(Editable s) { 

      // TODO Auto-generated method stub 
     } 
    }); 

寫內部onTextChanged()afterTextChanged()你的邏輯,檢查EditText數據的長度,如果是大於0設定drawableRight

edt.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.drawableRight, 0); 

別的清晰繪製

edt.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); 
+1

在這種情況下,我們如何執行onClick按鈕 –

0

將下面的代碼:

  1. 添加TextWatcherEditText
  2. 它會檢查長度。
  3. 如果它大於0,我們將刪除圖標添加到右邊的drawable。
  4. 如果它是0,那麼所有圖標都將被刪除。

您可能還需要與填充嘗試,否則你的文本將重疊的圖標,當它是隻要EditText本身。

mEditText.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
    } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
    } 

    @Override 
    public void afterTextChanged(Editable s) { 
     if(s.length() > 0) { 
      mEditText.setCompoundDrawablesWithIntrinsicBounds(0, 0, android.R.drawable.ic_delete, 0); 
     } else { 
      mEditText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); 
     } 
    } 
}); 
相關問題