1.说明自定义带删除功能的EditText有两种方法,第一种是用组合视图的方法,即在一个view视图里面左侧放置一个EditText,右侧放置一个ImageView,但是这样增加了视图的层次,而且对输入内容的长度要做一定的处理。第二种是重新
1.说明
自定义带删除功能的EditText有两种方法,第一种是用组合视图的方法,即在一个view视图里面左侧放置一个EditText,右侧放置一个ImageView,但是这样增加了视图的层次,而且对输入内容的长度要做一定的处理。
第二种是重新定义EditText组件,增加相应的事件处理,即可达到很好的效果,效果图如下:
2.ClearEditText的JAVA类文件
public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { //EditText右侧的删除按钮 private Drawable mClearDrawable; private boolean hasFoucs; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { this(context, attrs, Android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { // 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片,获取图片的顺序是左上右下(0,1,2,3,) mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { mClearDrawable = getResources().getDrawable( R.drawable.edit_delete); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); // 默认设置隐藏图标 setClearIconVisible(false); // 设置焦点改变的监听 setOnFocusChangeListener(this); // 设置输入框里面内容发生改变的监听 addTextChangedListener(this); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (getCompoundDrawables()[2] != null) { int x = (int)event.getX(); int y = (int)event.getY(); Rect rect = getCompoundDrawables()[2].getBounds(); int height = rect.height(); int distance = (getHeight() - height)/2; boolean isInnerWidth = x > (getWidth() - getTotalPaddingRight()) && x < (getWidth() - getPaddingRight()); boolean isInnerHeight = y > distance && y <(distance + height); if (isInnerWidth && isInnerHeight) { this.setText(""); } } } return super.onTouchEvent(event); } @Override public void onFocusChange(View v, boolean hasFocus) { this.hasFoucs = hasFocus; if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } @Override public void onTextChanged(CharSequence s, int start, int count, int after) { if (hasFoucs) { setClearIconVisible(s.length() > 0); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }
--结束END--
本文标题: Android实现自定义带删除功能的EditText实例
本文链接: https://www.lsjlt.com/news/222724.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0