我想制作一个复合控件,它是一个带有清除按钮的 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/