android之自定義帶清除內容的EditText

android之自定義帶清除內容的EditText

     android在很多地方需要用輸入框EditText,輸入的內容可以完全清除,這樣做的好處,是在有的地方用戶體驗更好,比如用戶在註冊登錄的輸入框,可以在EditText右側加上一個按鈕,點擊清除用戶名等;一般傳統做法是在佈局裏面加按鈕,這樣感覺做法不是很好,網上研究了下,然後自己總結了一個demo分享下。有問題可以提出,歡迎討論學習。
xml佈局:
<div style="text-align: left;"><pre name="code" class="html"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <com.example.editviewtest.MyEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="輸入"
        />

</RelativeLayout>



自定義MyEditText:

public class MyEditText extends EditText {

	private Context mContext;
	private Drawable imgDel_Gray;
	private Drawable imgDel_Bule;

	public MyEditText(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public MyEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	public MyEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	/***
	 * 初始化
	 */
	public void init() {
		// TODO Auto-generated method stub
		imgDel_Gray = mContext.getResources().getDrawable(
				R.drawable.delete_gray);
		imgDel_Bule = mContext.getResources().getDrawable(R.drawable.delete);
		setDrawble();
		// 對EditText文本狀態監聽
		this.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
				setDrawble();
			}
		});
	}

	/***
	 * 設置圖片
	 */
	public void setDrawble() {
		if (this.length() < 1) {
			/****
			 * 此方法意思是在EditText添加圖片 參數: left - 左邊圖片id top - 頂部圖片id right - 右邊圖片id
			 * bottom - 底部圖片id
			 */
			this.setCompoundDrawablesWithIntrinsicBounds(null, null,
					imgDel_Gray, null);
		} else {
			this.setCompoundDrawablesWithIntrinsicBounds(null, null,
					imgDel_Bule, null);
		}
	}

	/***
	 * 設置刪除事件監聽
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (imgDel_Bule != null && event.getAction() == MotionEvent.ACTION_UP) {
			int eventX = (int) event.getRawX();
			int eventY = (int) event.getRawY();
			Rect rect = new Rect();
			getGlobalVisibleRect(rect);
			rect.left = rect.right - 50;
			if (rect.contains(eventX, eventY))
				setText("");
		}
		return super.onTouchEvent(event);
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章