简体   繁体   English

如何在 Android 的 EditText 视图中添加图标?

[英]How to add icon inside EditText view in Android ?

I want to add a "search" icon to appear inside an EditText in the left edge?我想添加一个“搜索”图标以显示在左边缘的EditText内? such as search box in Facebook Android app?例如 Facebook Android 应用中的搜索框?

Use the android:drawableLeft property on the EditText.在 EditText 上使用android:drawableLeft属性。

<EditText
    ...     
    android:drawableLeft="@drawable/my_icon" />

You can set drawableLeft in the XML as suggested by marcos , but you might also want to set it programmatically - for example in response to an event.您可以按照marcos 的建议在 XML 中设置 drawableLeft,但您可能还想以编程方式设置它 - 例如响应事件。 To do this use the method setCompoundDrawablesWithIntrincisBounds(int, int, int, int) :为此,请使用setCompoundDrawablesWithIntrincisBounds(int, int, int, int) 方法

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

// Set drawables for left, top, right, and bottom - send 0 for nothing
editTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

If you want to use Android's default drawable, you can use @android:drawable/ic_menu_search like this:如果你想使用 Android 的默认 drawable,你可以像这样使用@android:drawable/ic_menu_search

<EditText android:id="@+id/inputSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@android:drawable/ic_menu_search"
    android:hint="Search product.."
    android:inputType="textVisiblePassword"/>

Use :用 :

<EditText
    ..     
    android:drawableStart="@drawable/icon" />

use android:drawbleStart propery on EditText在 EditText 上使用android:drawbleStart 属性

    <EditText
        ...     
        android:drawableStart="@drawable/my_icon" />

Use a relative layout and set the button the be align left of the edit text view, and set the left padding of your text view to the size of your button.使用相对布局并将按钮设置为在编辑文本视图的左侧对齐,并将文本视图的左填充设置为按钮的大小。 I can't think of a good way to do it without hard coding the padding :/如果没有对填充进行硬编码,我想不出一个好方法:/

You can also use apk tool to sorta unzip the facebook apk and take a look at its layout files.您还可以使用apk 工具对 facebook apk 进行解压缩并查看其布局文件。

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

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