繁体   English   中英

如何在EditText中添加两个drawableRight?

[英]How to add two drawableRight in EditText?

我能够在android中轻松地在EditText中添加一个drawableRight ,并且在click事件中,在一个drawableRight情况下可以正常工作。 但是我在EditText需要两个drawableRight

因此,如何在EditText添加两个drawableRight 而且我还需要分别对两个drawableRight执行click事件。

例如,我想在EditText添加黄色的星星,如下图所示,然后单击最右边的图像,我要打开电话的通讯录,然后单击黄色的星星,我要呼叫用户的收藏夹号码列表。

那么我该怎么做呢? 任何想法?

多个可绘制

没有对此的本地支持,因此您在此处有两个选择:

简单的解决方案:创建一个线性布局,并在右侧带有两个图像视图,这些将成为您的可绘制对象。

困难的方法:扩展Drawable类并实现自己的onDraw方法,在该方法中您将绘制两个drawable。 比将那个用于您的文本视图。

你不能 TextView任一侧只能包含一个可绘制对象。 您唯一的选择是:

  1. 创建自定义View
  2. 采取一些ViewGroup子孙( RelativeLayout / FrameLayout / etc),然后将TextView和两个ImageView一起放入其中。

只需使用RelativeLayout将两个Drawable放入EditText中即可。 要设置内部填充,请将一个不可见的drawableRight放入EditText中:

/res/values/dimens.xml

<resources>
    <dimen name="iconSize">32dp</dimen>
</resources>

/res/layout/my_layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/editText"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:inputType="textAutoComplete"/>

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="@dimen/iconSize"
        android:layout_height="@dimen/iconSize"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_action_1"/>

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="@dimen/iconSize"
        android:layout_height="@dimen/iconSize"
        android:layout_toLeftOf="@+id/imageButton1"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_action_2"/>

</RelativeLayout>

在您的活动中:

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);

    EditText editText = (EditText) findViewById(R.id.editText);

    int iconSize = (int) getResources().getDimension(R.dimen.iconSize)

    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.ic_action_1);
    drawable.setBounds(0, 0, iconSize * 2, 0); // that is the trick!

    editText.setCompoundDrawables(null, null, drawable, null);

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM