Android with clear function input Box control Edittextwithdel

Source: Internet
Author: User

Record the next very useful Gizmo Edittextwithdel. is to add a small icon to the right of the input box on the Android system. Click the small icon to clear the contents of the input box, because the Android native EditText does not have this feature, so to achieve this function we need to rewrite edittext.
For example, the following:

The basic idea is to set the listener for the picture on the right. Click the picture on the right to clear the contents of the input box and hide the delete icon, since we can not directly set the EditText click event, so we use to remember the position we pressed to simulate the click event, with the input box Ontouchevent () method to simulate.

 PackageCom.xiaolijuan.edittextwithdeldome;ImportAndroid.content.Context;ImportAndroid.graphics.Rect;Importandroid.graphics.drawable.Drawable;Importandroid.text.Editable;ImportAndroid.text.TextWatcher;ImportAndroid.util.AttributeSet;ImportAndroid.util.Log;ImportAndroid.view.MotionEvent;ImportAndroid.widget.EditText;/** * @author: Adan * @description: Define your own EditText * @projectNamewith the delete function: Edittextwithdeldome * @date: 2016-02-28 * @time: 23:34 * * Public  class edittextwithdel extends EditText {    Private Final StaticString TAG ="Edittextwithdel";PrivateDrawable imginable;PrivateDrawable imgable;PrivateContext Mcontext; Public Edittextwithdel(Context context) {Super(context);        Mcontext = context;    Init (); } Public Edittextwithdel(context context, AttributeSet attrs,intDefstyle) {Super(Context, attrs, Defstyle);        Mcontext = context;    Init (); } Public Edittextwithdel(context context, AttributeSet attrs) {Super(context, attrs);        Mcontext = context;    Init (); }Private void Init() {imgable = Mcontext.getresources (). getdrawable (R.mipmap.icon_delete_gray); Addtextchangedlistener (NewTextwatcher () {@Override             Public void ontextchanged(Charsequence S,intStartintBefore,intCount) {}@Override             Public void beforetextchanged(Charsequence S,intStartintCountintAfter) {}@Override             Public void aftertextchanged(Editable s)            {setdrawable ();        }        });    Setdrawable (); }//Set Delete picture    Private void setdrawable() {if(Length () <1) {Setcompounddrawableswithintrinsicbounds (NULL,NULL,NULL,NULL); }Else{Setcompounddrawableswithintrinsicbounds (NULL,NULL, Imgable,NULL); }    }//Handling Delete events    @Override     Public Boolean ontouchevent(Motionevent event) {if(Imgable! =NULL&& event.getaction () = = motionevent.action_up) {intEventx = (int) event.getrawx ();intEventy = (int) Event.getrawy (); LOG.E (TAG,"Eventx ="+ Eventx +"; Eventy = "+ Eventy); Rect rect =NewRect ();            Getglobalvisiblerect (rect); Rect.left = Rect.right- -;if(Rect.contains (Eventx, Eventy)) SetText (""); }return Super. Ontouchevent (event); }@Override    protected void Finalize()throwsThrowable {Super. Finalize (); }}

Setdrawable () method, Setcompounddrawableswithintrinsicbounds (drawable left, drawable top, drawable right, drawable bottom) To set the icon on the top, bottom, left, and right, assuming that you do not want to display it somewhere, set to null.
Next we'll use it to set the activity's layout. An input box of our own definition, a button

<?

XML version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android" Android:layout_width="Match_parent"android:layout_height="Match_parent" Android:orientation="vertical"> <relativelayout android: Layout_width = "match_parent" android:layout_ Height = "60DP" android:layout_margin = "25DP" android:background = "#ffffff" ; <imageview android:id= "@+id/img" android:layout_width = "25DP" android:layout_height =" 30DP " android:layout_alignparentleft = "True" android:layout_centervertical = "true" android:layout_margin = "5DP" android:src = "@mipmap/ic_launcher" /> <ImageViewandroid:layout_width="Match_parent"android:layout_height= "1DP" Android:layout_alignparentbottom="true"android:layout_marginleft="2DP" android:layout_marginright="2DP"android:background="#56AB55" /> <Com.xiaolijuan.edittextwithdeldome.EditTextWithDel Android:id="@+id/et_phonenumber" Android:layout_width="Wrap_content" Android:layout_height="Wrap_content" Android:layout_alignparentbottom="true" Android:layout_alignparentright="true" Android:layout_alignparenttop="true" Android:layout_margin="2DP" Android:layout_torightof="@+id/img" Android:background="#ffffff" Android:hint="Please enter your mobile phone number" Android:maxlength="One" Android:phonenumber="true" Android:singleline="true"/> </relativelayout> <buttonandroid:id="@+id/btn"android:layout_width="Match_parent" android:layout_height="Wrap_content"android:layout_margin="25DP" Android:background="#56AB55"android:text="OK" /> </linearlayout>

Then is the interface code writing. Main test the input box

 PackageCom.xiaolijuan.edittextwithdeldome;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.text.TextUtils;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public  class mainactivity extends Activity {    PrivateEditText UserName;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        UserName = (EditText) Findviewbyid (R.id.et_phonenumber); Findviewbyid (R.ID.BTN). Setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {if(Textutils.isempty (Username.gettext (). toString ())) {Toast.maketext (Getapplicationcontext (),"Cell phone number is empty", Toast.length_long). Show ();return;            } toast.maketext (Getapplicationcontext (), Username.gettext (). toString (), Toast.length_long). Show ();    }        }); }}

Dome Download

Android with clear function input Box control Edittextwithdel

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.