源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android实现带有删除按钮的EditText示例代码

  • 时间:2020-09-02 10:48 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android实现带有删除按钮的EditText示例代码
[b]一、首先来看看效果[/b] [img]http://files.jb51.net/file_images/article/201612/2016127104853658.gif?2016117104922[/img] 这是一个带有删除按钮的输入文本框, 需要新建一个类继承自EditText, 先把代码贴出来, 然后在解释: [b]示例代码如下:[/b]
public class EditTextWithDel extends EditText {

 private final static String TAG = "EditTextWithDel";
 private Drawable imgInable;
 private Context mContext;

 public EditTextWithDel(Context context) {
  this(context, null, 0);
 }

 public EditTextWithDel(Context context, AttributeSet attrs) {
  this(context, attrs, 0);
 }

 public EditTextWithDel(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  mContext = context;
  init();
 }

 private void init() {
  imgInable = mContext.getResources().getDrawable(android.R.drawable.ic_delete);
  addTextChangedListener(new TextWatcher() {
   @Override
   public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

   }

   @Override
   public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

   }

   @Override
   public void afterTextChanged(Editable editable) {
    setDrawable();
   }
  });

  setDrawable();
 }

 // 设置删除图片
 private void setDrawable() {
  if (length() < 1) {
   setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
  } else {
   setCompoundDrawablesWithIntrinsicBounds(null, null, imgInable, null);
  }
 }

 // 处理删除操作


 @Override
 public boolean onTouchEvent(MotionEvent event) {
  if (imgInable != null && event.getAction() == MotionEvent.ACTION_UP) {
   int eventX = (int) event.getRawX();
   int eventY = (int) event.getRawY();
   Log.d(TAG, "(" + eventX + ", " + eventY + ")");
   Rect rect = new Rect();
   getGlobalVisibleRect(rect);
   rect.left = rect.right - 70;
   Log.d(TAG, rect.toString());
   if (rect.contains(eventX, eventY)) {
    setText("");
   }
  }

  return super.onTouchEvent(event);
 }

 @Override
 protected void finalize() throws Throwable {
  super.finalize();
 }
}
[b]解释如下[/b] 首先看一下[code]setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom)[/code]这个名字贼长的方法, 虽然名字很长, 其实这个方法用起来和简单, 就是设置左上右下的图片, 这个dome只需要设置右边的就行了, 可以看一下全部设置的效果 接着就是还要监听Touch, 这里要说一下[code]getRawX()[/code]和[code]getX()[/code]的区别, [code]getRawX()[/code]或者[code]getRawY()[/code]方法是以屏幕为参考, [code]getX()[/code]和[code]getY()[/code]方法是以容器为参考, 所以二者得到的值可能不一样. 之后在利用[code]getGlobalVisibleRect()[/code]方法得到视图的位置, 存放到rect中, 这里是以屏幕左上角为起点的, 所以前面用的是getRaw方法. 当然也可以 使用getLocalVisibleRect方法, 这个方法是以View的左上角为起点的, 所以用这个方法的话, 就得使用[code]getX()[/code]和[code]getY()[/code]方法来或获取触摸点的x和y值了. [b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对各位Android开发者们能有所帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部