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