1. 程式人生 > >android自定義view_ClearEditText帶清空按鈕的輸入框

android自定義view_ClearEditText帶清空按鈕的輸入框


建立一個類繼承EditText

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText
; import com.example.ztz.android_timer.R; /** * Created by ztz on 2017/12/19. * 自定義view_ClearEditText */ @SuppressLint("AppCompatCustomView") public class ClearEditText extends EditText implements View.OnFocusChangeListener, TextWatcher { private Drawable mClearDrawable; private boolean hasFocus; public
ClearEditText(Context context) { super(context); } public ClearEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ClearEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void
init() { // getCompoundDrawables() Returns drawables for the left(0), top(1), right(2) and bottom(3) mClearDrawable = getCompoundDrawables()[2]; // 獲取drawableRight if (mClearDrawable == null) { // 如果為空,即沒有設定drawableRight,則使用R.drawable.close這張圖片 mClearDrawable = getResources().getDrawable(R.drawable.close); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); setOnFocusChangeListener(this); addTextChangedListener(this); // 預設隱藏圖示 setDrawableVisible(false); } /** * 我們無法直接給EditText設定點選事件,只能通過按下的位置來模擬clear點選事件 * 當我們按下的位置在圖示包括圖示到控制元件右邊的間距範圍內均算有效 */ @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (getCompoundDrawables()[2] != null) { // 起始位置 int start = getWidth() - getTotalPaddingRight() + getPaddingRight(); // 結束位置 int end = getWidth(); boolean available = (event.getX() > start) && (event.getX() < end); if (available) { this.setText(""); } } } return super.onTouchEvent(event); } @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFocus = hasFocus; // 當輸入文字時,顯示圖示 if (hasFocus && getText().length() > 0) { setDrawableVisible(true); } else { setDrawableVisible(false); } } @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if (hasFocus) { setDrawableVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } protected void setDrawableVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } }