【问题标题】:Click listener for drawableleft in EditText in Android?在 Android 的 EditText 中单击 drawableleft 的侦听器?
【发布时间】:2016-02-12 13:05:40
【问题描述】:

是否可以在设计器中声明为 drawableleft 的可绘制对象上添加 OnClickListener

android:drawableLeft="@drawable/ic_password"

或者有什么办法可以在EditText的左侧添加一个ImageView

【问题讨论】:

标签: android imageview onclicklistener


【解决方案1】:

对于 drawableleft 点击监听器:

 editText.setOnTouchListener(new 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.getRawX() <= (editText.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width()))
        {
              // your action here
             return true;
        }
        return false;
    }
});

如果您想要 drawable right 的点击监听器,请使用以下条件

if(event.getAction() == MotionEvent.ACTION_UP) {
            if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) 

【讨论】:

  • 哇,非常感谢。这就是我一直在寻找的东西
  • 不要抄袭别人的答案。至少给他们一些荣誉。
  • 请注明原始答案。谢谢
【解决方案2】:

你可以通过RelativeLayout来实现:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp">

    <ImageView
        android:id="@+id/image_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_iamge"/>

    <EditText
        android:id="@+id/text_id"
        android:layout_toRightOf="@id/image_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginLeft="16dp"
        android:text="Your text" />

 </RelativeLayout>

并将onClickListener 添加到代码中的ImageView

【讨论】:

  • 我认为这是“或者有没有办法在 EditText 的左侧添加 ImageView”这个问题的正确答案
猜你喜欢
  • 1970-01-01
  • 2014-03-06
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
相关资源
最近更新 更多