如何创建带有十字(x)按钮的EditText?

Aru*_*ole 184 android android-edittext

是否有任何小部件EditText包含一个十字按钮,或者是否有任何属性可以EditText自动创建?我希望十字按钮删除写入的任何文本EditText.

Jay*_*mar 165

使用以下布局:

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="9dp"
    android:padding="5dp">

    <EditText
        android:id="@+id/calc_txt_Prise"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"  
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:textColor="@color/gray"
        android:textStyle="bold"
        android:hint="@string/calc_txt_Prise"
        android:singleLine="true" />

    <Button
        android:id="@+id/calc_clear_txt_Prise"      
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_gravity="right|center_vertical"
        android:background="@drawable/delete" />

</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

您还可以使用按钮的id并在其onClickListener方法上执行您想要的任何操作.

  • 这是一种低效的方式.yanchenko的答案是使用复合drawables的正确方法. (8认同)
  • 如果您碰巧选择此解决方案并注意到图像拉伸太多,您应该使用ImageButton而不是常规Button. (4认同)
  • 虽然这种解决方案"效率低下",但对盲人用户来说更容易获得.使用drawable将强制您的用户执行非常复杂的操作来清除文本 - 看到用户可以使用X按钮快速执行操作. (3认同)
  • 什么是低效率? (2认同)

yan*_*nko 118

如果你碰巧使用DroidParts,我刚刚加入ClearableEditText.

这是abs__ic_clear_holo_lightActionBarSherlock设置自定义背景和清除图标的样子:

在此输入图像描述

  • 最好的解决方案,因为该类扩展了`EditText`.谢谢@yanchenko (11认同)
  • 谢谢!如果你还可以在DroidParts中包含一个ClearableAutoCompleteTextView,那真的很酷.对于其他尝试这样做的用户:使用DroidParts库,从ClearableEditText复制代码,只需扩展AutoCompleteTextView. (4认同)
  • @stephanek.我已经在开发分支中修复了这个问题,将成为1.4.3版本的一部分. (2认同)
  • 这是炸弹!您也可以单独使用它,通过普通的TextWatcher更改TextWatcherAdapter依赖性。 (2认同)

Gul*_*han 28

这是一个kotlin解决方案.把这个辅助方法放在一些kotlin文件中 -

fun EditText.setupClearButtonWithAction() {

    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            val clearIcon = if (editable?.isNotEmpty() == true) R.drawable.ic_clear else 0
            setCompoundDrawablesWithIntrinsicBounds(0, 0, clearIcon, 0)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
    })

    setOnTouchListener(View.OnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= (this.right - this.compoundPaddingRight)) {
                this.setText("")
                return@OnTouchListener true
            }
        }
        return@OnTouchListener false
    })
}
Run Code Online (Sandbox Code Playgroud)

然后在onCreate方法中使用它,你应该好好去 -

yourEditText.setupClearButtonWithAction()
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你必须先添加R.drawable.ic_clear或清除图标.这个是来自google- https: //material.io/tools/icons/ ? icon = clear & style = baseline


kev*_*oid 18

通过Material Components for Android的2019解决方案:

将材料组件添加到您的gradle设置中:

implementation 'com.google.android.material:material:1.1.0-alpha09'
Run Code Online (Sandbox Code Playgroud)

或者,如果您尚未更新为使用AndroidX库,则可以通过以下方式添加它:

implementation 'com.android.support:design:28.0.0'
Run Code Online (Sandbox Code Playgroud)

然后

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_text"
    app:endIconMode="clear_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)

注意:app:endIconMode =“ clear_text”

如此处所述材料设计文档

  • 这应该是新接受的答案。就我而言,如果不更新到AndroidX库,就无法实现。 (4认同)

Eam*_*orr 16

Drawable x = getResources().getDrawable(R.drawable.x);
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
mEditText.setCompoundDrawables(null, null, x, null);
Run Code Online (Sandbox Code Playgroud)

其中,x是:

在此输入图像描述

  • 还是我们需要分配一个onClickListener吗?快速搜索给了我[这个](http://stackoverflow.com/questions/3554377/handling-click-events-on-a-drawable-within-an-edittext).猜猜更好的解决方案是使用Framelayout.谢谢! (8认同)

Die*_*rik 15

Android的支持libarary有一个SearchView类正是这样做的.(EditText虽然不是从中汲取,所以必须使用SearchView.OnQueryTextListener而不是a TextWatcher)

没有文字的搜索视图(和提示文字

在此输入图像描述

在XML中使用如下:

  <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="@string/SearchHint"
            app:iconifiedByDefault="false"
            app:queryHint="@string/SearchHint" />
Run Code Online (Sandbox Code Playgroud)


0x8*_*00D 12

因为drawable resource你可以使用标准的android图像:

http://androiddrawables.com/Menu.html

例如 :

android:background="@android:drawable/ic_menu_close_clear_cancel"
Run Code Online (Sandbox Code Playgroud)


And*_*onu 5

如果您不想使用自定义视图或特殊布局,可以使用9-patch制作(X)按钮.

示例:http://postimg.org/image/tssjmt97p/(我没有足够的积分在StackOverflow上发布图片)

右下黑色像素的交点表示内容区域.该区域之外的任何东西都是填充物.因此,要检测用户单击x,您可以设置OnTouchListener,如下所示:

editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                    if (motionEvent.getX()>(view.getWidth()-view.getPaddingRight())){
                        ((EditText)view).setText("");
                    }
                }
                return false;
            }
        });
Run Code Online (Sandbox Code Playgroud)

根据您的需求,此解决方案在某些情况下可以更好地工作.我更喜欢让我的xml不那么复杂.如果你想在左边有一个图标,这也很有帮助,因为你可以简单地将它包含在9补丁中.


Fra*_*cis 5

就像drawableEnd在你的EditText

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />
Run Code Online (Sandbox Code Playgroud)

并使用扩展来处理点击(或OnTouchListener直接在您的 上使用EditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}
Run Code Online (Sandbox Code Playgroud)

扩展用法:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}
Run Code Online (Sandbox Code Playgroud)


小智 5

清除文本:

“带有清晰文本尾随图标的文本字段。”

如果设置,当文本出现时会显示一个图标,按下它会清除输入的文本。

    ...
    app:endIconMode="clear_text">
?
    ...
?
</com.google.android.material.textfield.TextInputLayout>
Run Code Online (Sandbox Code Playgroud)

我把它留在这里:

材料网

例子
例子