是否有像EditText这样包含交叉按钮的小部件,或者是否有自动创建EditText的属性?我想用十字按钮删除任何写在EditText中的文本。


当前回答

对于可绘制的资源,您可以使用标准的android图像:

http://androiddrawables.com/Menu.html网站档案

例如:

android:background="@android:drawable/ic_menu_close_clear_cancel"

其他回答

Use

android:drawableRight="@android:drawable/ic_input_delete"

这是一个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
    })
}

然后像下面那样在onCreate方法中使用它,你应该很好

yourEditText.setupClearButtonWithAction()

顺便说一句,你必须添加R.drawable。Ic_clear或清除图标。这个来自谷歌- https://fonts.google.com/icons?selected=Material%20Icons%20Outlined%3Aclear%3A

对于可绘制的资源,您可以使用标准的android图像:

http://androiddrawables.com/Menu.html网站档案

例如:

android:background="@android:drawable/ic_menu_close_clear_cancel"
Drawable x = getResources().getDrawable(R.drawable.x);
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
mEditText.setCompoundDrawables(null, null, x, null);

式中x为:

在你的EditText中添加drawableEnd这样的十字:

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

并使用扩展处理点击(或使用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
    }
}

扩展用法:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}