【问题标题】:clickable drawable inside EditText in androidandroid中EditText内的可点击drawable
【发布时间】:2013-07-09 20:59:02
【问题描述】:

我有一个 EditText,里面有一个 drawable。我想让drawable可点击,这样当用户点击drawable时我可以有一个特定的动作。我怎么做?我的 EditText 是:

<EditText
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="5dp"
        android:drawableRight="@drawable/question_mark"
        android:hint="phone number"
        android:imeActionId="@+id/phone_num"
        android:maxLines="1"
        android:singleLine="true"
        android:textColor="#000000" />

【问题讨论】:

  • 为什么EditText 不是ImageView?添加android:onClick="phoneClicked" 属性,然后实现public void phoneClicked( View view ) {...}。
  • 我的设计要求 question_mark 图像出现在 EditText 视图中。
  • 知道了,据我所知,你不能这样做,你必须制作一个白色背景的容器并在它旁边添加 EditText 和一个 Image,然后让 Image onClick。换句话说,您会产生图像在文本区域内的错觉,但实际上并非如此。如果有人知道我错了,请赐教。
  • RelativeLayout 可能允许您将按钮向上/向下放置到 EditText

标签: android android-layout textview drawable android-edittext


【解决方案1】:

正如 Gina 上面所建议的,您可以通过使用 RelativeLayout 而不是 drawableRight 属性来实现这一点。下面的代码将图像视图放在 EditText 的右侧

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

<EditText
    android:id="@+id/phone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="5dp"
    android:hint="phone number"
    android:imeActionId="@+id/phone_num"
    android:maxLines="1"
    android:singleLine="true"
    android:textColor="#000000" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignRight="@+id/phone"
        android:layout_marginRight="10dp"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

【讨论】:

  • 我知道该怎么做。我一直在寻找更简单的东西。但在有人给出更好的答案之前,我会接受这个。
  • 这不能正常工作,文字在图像下方。在高标准应用中也不例外。
  • 它工作正常..如果你给edittext 40dp的填充从右边(我给出的代码)文本将在图像之前完成并且它们不会折叠。
  • 你也可以做 android:layout_alignLeft="@+id/imageView1" 保持匹配父项
【解决方案2】:
phone.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            final int DRAWABLE_RIGHT = 2;

            if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if(motionEvent.getRawX() >= (phone.getRight() - phone.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    //Here is your code when you click drawable right
                    return true;
                }
            }
            return false;
        }
    });

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 2012-06-05
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多