Android Studio EditText Click on the icon to clear the text content

Source: Internet
Author: User
Tags deprecated

This article is following the custom EditText style after the function enhancement, for the actual application project has the very big reference opinion, the interested friend may step on the previous article, "The Android studion custom EditText style". Specifically, clear the EditText text content function code as follows :

 PackageCom.liheng;ImportAndroid.content.Context;;;;Importandroid.text.Editable;ImportAndroid.text.TextWatcher;ImportAndroid.util.AttributeSet;ImportAndroid.view.MotionEvent;ImportAndroid.widget.EditText;ImportMYSELF.MYAPPLICATION.R;/** * First step: * Create a class and inherit the class of EditText, implement the three constructors of the parent class * We only implement a constructor with one parameter, two parameters, three parameters, with four parameters for the moment. Public  class myedittext extends EditText {    /** * Second Step: * Declare 3 variables: Two picture objects (the value of the variable is obtained by instantiating the object, * in the Java world, except the basic data type and static members are not objects, * everything else is an object.) The class is also an object The object of the class, the picture is the object of the Drawable class) * 1. When the EditText text content is empty, the right empty icon should be gray, and clicking is no effect at this time * 2. When the EditText text content is not empty, the right empty icon should be blue, click to clear the EDI Ttext text Content * 3. Context Object * /    PrivateDrawable Imageblue;PrivateDrawable Imagegray;PrivateContext Mycontext;/** * Implement the three constructor methods of the EditText parent class * These three methods must call the custom initialization function init () method */     Public Myedittext(Context context) {Super(context);    Init (context); } Public Myedittext(context context, AttributeSet attrs) {Super(context, attrs);    Init (context); } Public Myedittext(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);    Init (context); }/** * Initialization method: The three global variables used to initialize the declaration: Imageblue,imagegray,mycontext * and is responsible for listening for changes to the EditText text content */    Private void Init(Context context) { This. Mycontext = Context;/** * Get Picture resources: * The first way: (Deprecated, deprecated, * Also note that the R file import package should be the package under its own project, * because the picture resource is in its own project directory): *         Imageblue = Mycontext.getresources (). getdrawable (R.drawable.delete);         * * The second way: (user recommended, the project will be error?)          * Call Getdrawable () a method with two parameters. The second parameter is set to NULL * Imageblue = Mycontext.getresources (). getdrawable (R.drawable.delete, NULL); * Third Way: (officially recommended by Google), Mycontext for itself the context object declared * Imageblue = contextcompat.getdrawable (Mycontext, R.D         Rawable.delete); */Imageblue = contextcompat.getdrawable (Mycontext, r.drawable.delete); Imagegray = contextcompat.getdrawable (Mycontext, R.drawable.delete_gray);/** * Set the text listener (EditText the corresponding callback function when the text content changes) * ontextchanged () edittext The text content changes when it is triggered * Beforetextchan Ged () edittext text content changes before triggering * aftertextchanged () edittext text content changes after triggering * * For this item, emptying edittext should be in edittext text content more Trigger after Change * * /Addtextchangedlistener (NewTextwatcher () {@Override             Public void beforetextchanged(Charsequence S,intStartintCountintAfter) {}@Override             Public void ontextchanged(Charsequence S,intStartintBefore,intCount) {}@Override             Public void aftertextchanged(Editable s) {the position of the empty picture is set after the text is changed.SetImage (); }        });//The location of the empty picture should also be set at the beginningSetImage (); }/** * Set Picture position method * When length () is greater than 0, that is, when there is text content in EditText, the picture is blue * when length () is less than 0, that is, the picture is gray when there is no text content in the EditText * Setcompounddrawableswithintrinsicbounds () Four parameters for left upper right bottom */    Private void  setimage(){if(Length () >0) {Setcompounddrawableswithintrinsicbounds (NULL,NULL, Imageblue,NULL); }Else{Setcompounddrawableswithintrinsicbounds (NULL,NULL, Imagegray,NULL); }    } Public Boolean ontouchevent(Motionevent event) {Switch(Event.getaction ()) {//Match finger leave EditText             CaseMOTIONEVENT.ACTION_UP:x y coordinate when you get your finger out of edittext                intx = (int) event.getrawx ();inty = (int) Event.getrawy ();//Create a rectangleRect rect =NewRect ();//Let the width of the rectangle be equal to the width of the edittext, so that the rectangle is higher than the EditTextGetglobalvisiblerect (rect);//Shorten the rectangle to the right of 50 widthRect.left = Rect.right- -;//If the x and Y coordinates are in the rectangle, you click the xx image on the right and empty the input box                if(Rect.contains (x, y)) {SetText (""); } Break;default: Break; }return Super. Ontouchevent (event); }}

Custom Myedittext This class is actually the same as the EditText control we dragged in the layout file because Myedittext inherits from the parent edittext. But we should include the full package name when we call it in the layout file. As follows:

<?xml version= "1.0" encoding= "Utf-8"?><Relativelayout xmlns:android="Http://"    Xmlns:tools="Http://" Android:id="@+id/activity_main"    Android:layout_width="Match_parent" Android:layout_height="Match_parent"    Android:paddingbottom="@dimen/activity_vertical_margin"    Android:paddingleft="@dimen/activity_horizontal_margin"    Android:paddingright="@dimen/activity_horizontal_margin"    Android:paddingtop="@dimen/activity_vertical_margin"    Tools:context="Myself.myapplication.MainActivity">    <Com.liheng.MyEditText        Android:layout_width="500DP"        Android:layout_height="50DP"        Android:inputtype="Textpersonname"        Android:text="Name"        Android:ems="Ten"        Android:layout_alignparenttop="true"        Android:layout_alignparentleft="true"        Android:layout_alignparentstart="true"        Android:layout_marginleft="45DP"        Android:layout_marginstart="45DP"        Android:layout_margintop="49DP"        Android:id="@+id/edittext"        Android:paddingleft="10DP"        Android:paddingright="10DP"        Android:background="@drawable/select_edittext"/>    <Com.liheng.MyEditText        Android:layout_width="500DP"        Android:layout_height="50DP"        Android:inputtype="Textpersonname"        Android:text="Name"        Android:ems="Ten"        Android:layout_below="@+id/edittext"        Android:layout_alignleft="@+id/edittext"        Android:layout_alignstart="@+id/edittext"        Android:layout_margintop="89DP"        Android:id="@+id/edittext2"        Android:paddingleft="10DP"        Android:background="@drawable/select_edittext"/></relativelayout>

Attached to the actual:

A closer look reveals that the empty icon for the first input box is a bit to the left, because I added a line of android:paddingright= "10DP" to the XML layout file of the first input box. So, for the location of the empty icon, We can make specific adjustments based on the resolution size of the phone.

icon Material:

Android Studio EditText Click on the icon to clear the text content

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.