在開(kāi)發(fā)過(guò)程中不可避免的總會(huì)遇到比如登錄注冊(cè)、用戶(hù)信息修改等初厚,這時(shí)候又是不可避免的會(huì)用到EditText控件炎码。這個(gè)控件的使用頻率雖然幾乎類(lèi)似我們吃飯用“筷子”的頻率,but能不能用出花樣裆装,用的有技術(shù)就看你有沒(méi)有下功夫嘍踱承。
代碼實(shí)現(xiàn):
import android.content.Context;
import android.graphics.Rect;
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.ktc.sczwdemo.R;
import com.ktc.utils.ResUtils;
/**
* @Date 2016-5-13 下午2:23:23
* @Author Arvin
* @Description 可刪除且?guī)в衐rawableLeft的EditText
*/
public class EditWithDelView extends EditText {
private final static String TAG = "EditWithDelView";
private Drawable imgDisable;
private Drawable imgAble;
private Context mContext;
public EditWithDelView(Context context) {
super(context);
mContext = context;
init();
}
public EditWithDelView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
init();
}
public EditWithDelView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
init();
}
private void init() {
imgAble = ResUtils.getDrawable(R.drawable.delete);
addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void afterTextChanged(Editable s) {
setDrawable();
}
});
this.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus&&length()>=1){
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], null, imgAble, null);
}else{
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], null, null, null);
}
}
});
}
//根據(jù)字符長(zhǎng)度加載提示Drawable
private void setDrawable() {
if(length() < 1){
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], null, null, null);
}else if(isFocused()){
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], null, imgAble, null);
}
}
//響應(yīng)觸摸點(diǎn)擊事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (imgAble != 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;
rect.top = rect.bottom - 50;
if(rect.contains(eventX, eventY)){
setText("");
setCompoundDrawablesWithIntrinsicBounds(getCompoundDrawables()[0], null, null, null);
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
里面可根據(jù)需要替換imgDisable和imgAble兩個(gè)資源。
- 使用方法:在Xml中像普通EditText一樣直接引用即可
謹(jǐn)以作為開(kāi)發(fā)記錄哨免,如果有幫到您茎活,記得點(diǎn)贊哦