android-layout - 如何使用清除按钮制作可重复使用的 EditText?

标签 android-layout android-widget android android-custom-view

我想制作一个复合控件,它是一个带有清除按钮的 EditText。由于主要功能将是 EditText 功能,我希望它可以在具有 EditText 的所有属性的布局 xml 中声明。但是,它实际上将是一个带有 EditText 和 ImageButton 的 LinearLayout。

此外,我希望它像代码中的 EditText 一样使用,所以我可以将它作为替代品放入。

到目前为止我有这个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@android:drawable/editbox_background" >
    <EditText 
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:background="#FFF" />
    <ImageButton
        android:id="@+id/clear"
        android:src="@drawable/clear_text"
        android:background="#FFF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />
</LinearLayout>

但我不确定如何进行。如果我需要它是一个 LinearLayout 以便使用此布局,我该如何定义一个扩展 EditText 的控件?或者我唯一的选择是在 onDraw() 中手动绘制 x 并自己处理点击?

最佳答案

 public class myedittext extends LinearLayout{
 EditText e1;
  ImageButton ib;
  OnClickListener cleartext;
 public myedittext(Context c){
  super(c);
   String inflater=context.LAYOUT_INFLATER_SERVICE;
  LayoutInflater lif;
  li=(LayoutInflater)getContext().getSystemService(inflater);
  li.inflate((R.layout.yourlayoutname,this,true);
 e1=(EditText)findViewById(R.id.editText);
   ib=(ImageButton)findViewById(R.id.clear);


  cleartext = new OnClickListener(){

    @Override
    public void onClick(View v) {

        e1.setText("");
    }
   };
  ib.setOnClickListener(cleartext);
 }
   }

关于android-layout - 如何使用清除按钮制作可重复使用的 EditText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238875/

相关文章:

Android - 如何设置所有屏幕的背景颜色?

安卓风格说明

android - 语法错误插入;和 } 来完成声明?

java - 无法使用 JDBC 将 Android 应用程序连接到使用 XAMPP 的 MYSQL 数据库

android - IllegalArgumentException:在 Google MapView 的 zoomOut 期间宽度和高度必须 > 0

java - 以编程方式调整线性布局的高度

android - 如何为 Android 创建 3d 标签球体 UI

android-layout - 如何知道 View 何时实际显示

android - 从 Intent 调用另一个应用程序杀死我正在运行的应用程序

android - 将 FrameLayout 设置为 xml 布局 android 的背景