【问题标题】:How to add icon inside EditText view in Android ?如何在 Android 的 EditText 视图中添加图标?
【发布时间】:2020-06-14 16:47:17
【问题描述】:

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

【问题讨论】:

    标签: android


    【解决方案1】:

    在 EditText 上使用 android:drawableLeft 属性。

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

    【讨论】:

    • 对不起,不清楚的问题,我想添加一个按钮,所以当我点击它时,它会做一些动作
    • 考虑到搜索标题,这正是我所期望的解决方案。
    • 另外,使用drawablePadding 属性调整填充。
    • 那么该可绘制图标的大小应该是多少,我应该将它放在哪个文件夹中?
    • @KalpeshLakhani :根据android设计指南,通常edittext和drawables应该是32dp:developer.android.com/design/style/metrics-grids.html
    【解决方案2】:

    您可以按照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 - 这就是我删除答案的原因。除了原始 XML 解决方案之外,我现在已经进行了编辑以包含一个编程解决方案。
    • 如何以编程方式隐藏图标?什么时候点击编辑框?
    • @Hunt - 只需在单击视图时将 coumound drawable 设置为 null
    【解决方案3】:

    如果你想使用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"/>
    

    【讨论】:

      【解决方案4】:

      使用:

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

      【讨论】:

        【解决方案5】:

        在 EditText 上使用 android:drawbleStart 属性

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

        【讨论】:

          【解决方案6】:

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

          您也可以使用apk tool 来解压 facebook apk 并查看其布局文件。

          【讨论】:

          • 我想提一下,反编译在许多国家都是违法的,例如在整个欧盟,所以请小心:)
          猜你喜欢
          • 1970-01-01
          • 2017-01-26
          • 2016-06-22
          • 2018-02-15
          • 1970-01-01
          • 2012-12-08
          • 1970-01-01
          • 1970-01-01
          • 2021-12-10
          相关资源
          最近更新 更多