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


141

我想添加一个“搜索”图标以显示EditText在的左侧边缘中吗?例如Facebook Android应用中的搜索框?

Answers:


432

使用android:drawableLeftEditText上的属性。

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

3
抱歉,您不清楚问题,我想添加一个按钮,所以当我单击它时,它会执行一些操作
Adham 2010年

20
给定搜索标题,这只是我期望的解决方案。
Thomas Ahle 2010年

32
另外,使用drawablePadding属性调整填充。
Ryan R

那么该可绘制图标的大小应该是多少,应该放置在哪个文件夹中?
Kalpesh Lakhani 2014年

2
@KalpeshLakhani:通常,根据android设计指南,edittext和drawables应该为32dp:developer.android.com/design/style/metrics-grids.html
Lee Yi Hong

30

您可以按照marcos的建议在XML中设置drawableLeft ,但是您可能还希望通过编程方式设置它-例如,响应事件。为此,请使用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);

这将背景设置为EditText,而不是问题中明确提到的“左边缘”上的图标/图像。
Paresh Mayani

@Paresh-这就是为什么我删除答案的原因。我现在进行了编辑,除了原始的XML解决方案之外,还包括一个编程解决方案。
彼得·阿杰泰

1
如何以编程方式隐藏图标?什么时候单击编辑框?
2012年

1
@Hunt- null单击视图时,只需将可绘制的coumound设置为即可。
彼得·阿杰泰

27

如果要使用Android的默认可绘制对象,则可以这样使用@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"/>



-1

使用相对布局,然后将按钮设置为“编辑文本”视图的左侧,然后将文本视图的左侧填充设置为按钮的大小。如果不对填充进行硬编码,我想不出一个好方法:

您还可以使用apk工具对Facebook apk进行解压缩,并查看其布局文件。


1
我想提一提,反编译是违法的许多国家,例如在整个欧盟,所以请小心:)
帕维尔Byszewski
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.