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


当前回答

使用以下布局:

<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>

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

其他回答

Android的支持库中有一个SearchView类就是这样做的。(虽然不是从EditText派生的,所以必须使用一个SearchView。OnQueryTextListener代替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" />

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

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

例如:

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

Android材质设计组件2020解决方案:

添加材质组件到你的gradle设置:

从这里查找最新版本:https://maven.google.com/

implementation 'com.google.android.material:material:1.3.0'

或者如果你还没有更新到使用AndroidX库,你可以这样添加:

implementation 'com.android.support:design:28.0.0'

Then

<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>

注意:app:endIconMode="clear_text"

正如这里所讨论的材料设计文档

Use

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

下面是带有小部件的完整库: https://github.com/opprime/EditTextField

要使用它,你应该添加依赖:

compile 'com.optimus:editTextField:0.2.0'

在layout.xml文件中,你可以设置小部件:

xmlns:app="http://schemas.android.com/apk/res-auto"

app:clearButtonMode,can有这样的值: 从来没有 总是 whileEditing unlessEditing 应用:clearButtonDrawable

实际例子: