簡體   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