Android:如何通过右侧的十字按钮清除EditText [英] Android: How to clear an EditText by cross Button in the right side

查看:163
本文介绍了Android:如何通过右侧的十字按钮清除EditText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个EditText进行搜索,其中在左侧包含一个搜索图标,在该图标的右侧包含了

I have created an EditText for search, which contains on the left side a search icon and on the right side of icon:

<EditText
    android:id="@+id/Search"
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:drawableLeft="@android:drawable/ic_menu_search"
    android:drawableRight="@android:drawable/ic_delete"
    android:hint="Search Product .." >
</EditText>

我想知道单击十字按钮时如何清除EditText的内容.

I want to know how can I clear the content of EditText when I click the cross button.

谢谢.

推荐答案

@aristo_sh从

An improved answer by @aristo_sh from Handling click events on a drawable within an EditText

    mQueryEditText.setOnTouchListener(new OnTouchListener() {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                int leftEdgeOfRightDrawable = mQueryEditText.getRight() 
                      - mQueryEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width();
                // when EditBox has padding, adjust leftEdge like
                // leftEdgeOfRightDrawable -= getResources().getDimension(R.dimen.edittext_padding_left_right);
                if (event.getRawX() >= leftEdgeOfRightDrawable) {
                    // clicked on clear icon
                    mQueryEditText.setText("");
                    return true;
                }
            }
            return false;
        }
    });

这篇关于Android:如何通过右侧的十字按钮清除EditText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆