android 代碼設置editText的 drableRight和drableRight的點擊事件

需求是這樣子的,需要在Edittext最右邊加一個清除文字的小圖標,解決思路有兩個,1 使用相對佈局,設置ImageView的點擊事件,2設置Edittext的drableRight和單機時間。

核心代碼如下:

/**
* 註冊手機號輸入框的textChange事件
*/
private class InputPhoneNumberTextChangeListener implements TextWatcher{


@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!TextUtils.isEmpty(s.toString())){
Drawable drawable = getResources().getDrawable(R.drawable.close);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //設置邊界
phoneNumberEdt.setCompoundDrawables(null, null, drawable, null);//畫在右邊
}else{
phoneNumberEdt.setCompoundDrawables(null, null, null, null);//畫在右邊
}
}


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

}


@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub

}

}

設置drableRiht的點擊事件,通過Edittext的touch事件來判斷的哈!

//設置手機號的右邊drable的點擊事件
private class DrableTouchListener implements OnTouchListener{


@Override
public boolean onTouch(View arg0, MotionEvent event) {
// et.getCompoundDrawables()得到一個長度爲4的數組,分別表示左右上下四張圖片
Drawable drawable = phoneNumberEdt.getCompoundDrawables()[2]; 
//如果右邊沒有圖片,不再處理
if (drawable == null) return false; 
//如果不是按下事件,不再處理 
if (event.getAction() != MotionEvent.ACTION_UP) 
return false; 
if (event.getX() > phoneNumberEdt.getWidth() - phoneNumberEdt.getPaddingRight() - drawable.getIntrinsicWidth()){ 
phoneNumberEdt.setText(""); 
}
return false; 
}

}

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