在editText 搶占焦點(diǎn)的問題上,采用攔截事件的方式處理,自定義View。
1.繼承類View類,如圖所示輸入框,繼承自EditText,點(diǎn)擊右側(cè)刪除按鈕,editText數(shù)據(jù)清空
此輸入框代碼如下:
當(dāng)通過以下代碼設(shè)置右側(cè)刪除圖片時(shí)
setCompoundDrawablesWithIntrinsicBounds(null, null, mRightIcon, null);
editText會搶占焦點(diǎn),點(diǎn)擊drawable 無法響應(yīng),解決方法可通過觸摸的位置,來判斷用戶的需求。
`
/**
* 監(jiān)聽刪除操作
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!this.isEnabled() || event.getAction() != MotionEvent.ACTION_UP) {
return super.onTouchEvent(event);
}
// 清除按鈕,獲取焦點(diǎn),控件可用時(shí)清空
Drawable rightIcon = mRightIconLoader.getRightIcon();
if (rightIcon != null) {
int x = (int) event.getX();
int y = (int) event.getY();
int padding = this.getPaddingRight();
if (x >= (this.getRight() - this.getLeft()
- rightIcon.getBounds().width() - padding - PRESS_MARGIN)
&& x <= (this.getRight() - this.getLeft())
&& y >= (this.getPaddingBottom() - PRESS_MARGIN)
&& y <= (this.getHeight() - this.getPaddingTop() + PRESS_MARGIN)) {
//監(jiān)聽器,讓外部獲得事件
mRightIconLoader.onRightIconTouched();
event.setAction(MotionEvent.ACTION_CANCEL);
} else {
onTouch();
}
} else {
onTouch();
}
return super.onTouchEvent(event);
} `
2.自定義組合類View,繼承自ViewGroup
在ViewGroup類對事件進(jìn)行攔截,不傳給子View,使用onInterceptTouchEvent()用于處理事件并改變事件的傳遞方向。
`
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (!this.isEnabled() || event.getAction() != MotionEvent.ACTION_UP) {
return super.onTouchEvent(event);
}
int x = (int) event.getX();
int y = (int) event.getY();
// 清除按鈕,獲取焦點(diǎn),控件可用時(shí)清空
if (mImageListener != null) {
Drawable rightIcon = mImageListener.getIcon();
if (rightIcon != null) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) rightIcon;
mJDRImageView.setImageBitmap(bitmapDrawable.getBitmap());
}
}
if (x >= mJDRImageView.getLeft() && x <= mJDRImageView.getRight() && y >= mJDRImageView.getTop() && y <= mJDRImageView.getBottom()) {
if (mImageListener != null) {
mImageListener.onIconTouched();
}
event.setAction(MotionEvent.ACTION_CANCEL);
}
return super.onInterceptTouchEvent(event);
}`