如何禁用Android EditText中Drawable右侧(即EditText内图标)的onClick事件中的粘贴功能

3

我有一个包含图标的 EditText

<EditText
    android:id="@+id/myedittext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawableRight="@mipmap/microphone"/>

我为EditText右侧的Drawable设置了onClickListener

myeditText.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if(event.getAction() == MotionEvent.ACTION_UP) {
                if(event.getRawX() >= (myeditText.getRight() - myeditText
      .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {  
                    // your action here
                    Toast.makeText(getApplicationContext(),
                            "speak",Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
            return false;
        }
    });

当我点击EditText右侧的图标时,会显示一个Toast并起作用,但是还会在EditText上显示粘贴选项。如何在单击右侧图标时删除粘贴选项?


你修好了吗? - Vucko
4个回答

2

嗯,已经过去大约3年了。然而,对于像我这样可能面临这个挑战的人来说:解决方案是在ACTION_DOWN中也返回true,但仅在ACTION_DOWN时调用监听器,并同样返回true。 在这种情况下,您首先检查所单击的区域是否与图标的相应区域相对应,然后再继续检查向上或向下的动作。类似于:

最初的回答:

Return true in ACTION_DOWN but only call the listener on ACTION_DOWN, returning true as well.

@Override
public boolean onTouch(View v, MotionEvent event) {
        final int DRAWABLE_LEFT = 0;
        final int DRAWABLE_TOP = 1;
        final int DRAWABLE_RIGHT = 2;
        final int DRAWABLE_BOTTOM = 3;


        if (event.getRawX() >= (myeditText.getRight() - myeditText
                .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
            if (event.getAction() == MotionEvent.ACTION_UP) {
                // your action here
                listener.onClick(v);
                return true;
            }

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                return true;
            }
        }

        return false;
    }

1
在我的情况下,从 ACTION_UP 更改为 ACTION_DOWN 产生了效果。当然,行为稍微有所改变。光标仍然会跳到文本的末尾。

1

只需将 android:longClickable="false" 设置为编辑框。


0

您可以查看this问题,了解如何禁用粘贴

但我建议您采用另一种方法,而不是禁用粘贴。观察WhatsApp的麦克风按钮+EditText位置,我注意到它们是两个不同的元素,这就是您可以做的。将您的EditText包装在一个水平的LinearLayout中,并在右侧放置一个带有麦克风的按钮。我希望您能够成功实现它,并理解我的想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接