我想我找到了一个非常优雅的解决方案:我在文本框中使用了一个 Drawable(在我的情况下为 drawableRight),并且我在 drawable 上分配了一个单击侦听器,用于执行数字和文本模式之间的切换。我可以使用从在 EditText 中的可绘制对象上处理单击事件中获取的一个小技巧,仅在可绘制对象上分配一个侦听器:
public class MyEdittextextends EditText {
private Drawable drawableRight;
private Drawable drawableLeft;
private Drawable drawableTop;
private Drawable drawableBottom;
//YOUR STUFF HERE
@Override
public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
if (right != null) {
drawableRight = right;
}
if (left != null) {
drawableLeft = left;
}
super.setCompoundDrawables(left, top, right, bottom);
}
View.OnClickListener _leftDrawableClickListener = null;
View.OnClickListener _rightDrawableClickListener = null;
public void setLeftDrawableClickListener(View.OnClickListener clickListener) {
_leftDrawableClickListener = clickListener;
}
public void setRightDrawableClickListener(View.OnClickListener clickListener) {
_rightDrawableClickListener = clickListener;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int x, y;
Rect bounds;
x = (int) event.getX();
y = (int) event.getY();
// this works for left since container shares 0,0 origin with bounds
if (drawableLeft != null) {
bounds = drawableLeft.getBounds();
if (bounds.contains(x - fuzz, y - fuzz)) {
try {
_leftDrawableClickListener.onClick(this);
} catch (Exception e) {
}
if (consumeEvent) {
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
}
} else if (drawableRight != null) {
bounds = drawableRight.getBounds();
if (x >= (this.getRight() - bounds.width() - fuzz) && x <= (this.getRight() - this.getPaddingRight() + fuzz) && y >= (this.getPaddingTop() - fuzz) && y <= (this.getHeight() - this.getPaddingBottom()) + fuzz) {
try {
_rightDrawableClickListener.onClick(this);
} catch (Exception e) {
}
if (consumeEvent) {
event.setAction(MotionEvent.ACTION_CANCEL);
return false;
}
}
} else if (drawableTop != null) {
// not implemented yet
} else if (drawableBottom != null) {
// not implemented yet
}
}
return super.onTouchEvent(event);
}
@Override
protected void finalize() throws Throwable {
drawableRight = null;
drawableBottom = null;
drawableLeft = null;
drawableTop = null;
super.finalize();
}
}
创建自定义 EditText 后,我在 Activity 中使用了此代码
myEdittext = (EditText) findViewById(R.id.myEdittext);
myEdittext.setRightDrawableClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (myEdittext.getInputType() != InputType.TYPE_CLASS_TEXT) {
myEdittext.setInputType(InputType.TYPE_CLASS_TEXT);
myEdittext.setRawInputType(InputType.TYPE_CLASS_TEXT);
myEdittext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.keyboard_123, 0);
} else {
myEdittext.setRawInputType(InputType.TYPE_CLASS_NUMBER);
myEdittext.setInputType(InputType.TYPE_CLASS_NUMBER);
myEdittext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.keyboard_abc, 0);
}
}
});
这是结果:当 EditText 首次显示时,如下所示
然后点击“ABC”图片变成这样
希望这可以帮助某人