Thursday, April 19, 2012

How to make a reusable EditText with clear button?

I want to make a compound control that is a EditText with a clear button. Since the main functionality will be the EditText functionality, I want it to be declarable in layout xmls with all the attributes of an EditText. But, it is actually going to be a LinearLayout with an EditText and an ImageButton in it.



Also, I want it to be used just like an EditText in the code, so I can just drop it in as a replacement.



I have this layout so far:



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


But I am unsure how to proceed. How do I define a control that extends EditText if I need it to be a LinearLayout in order to use this layout? Or is my only option to draw the x manually in onDraw() and handle clicks myself?





No comments:

Post a Comment