Android Learning Mini Demo (22) TextView with delete button

Source: Internet
Author: User
Tags gety

Many times, there are some very simple needs, such as you use a button to pop up a page, after selecting an object, you will have some of the object's properties, such as the name, and so on, displayed on the button.

and follow, and will think, can you just choose the object to clear, such as the button on the text to remove, this time, you will hope, if the button can also have more than one icon, a click, the current control of the text and so clear off the good, and will correspond to the callback function, let us deal with a number of things, That's great.

Unfortunately, Android does not provide ready-made controls for us to use, but in a different perspective, this is not a pity, because we can achieve this effect on their own, it is a very interesting thing ah.

Even if sometimes, the implementation is very simple, just a little more things, but when we put it into effect, the feeling of satisfaction will still arise Ah, right!

What you want to do now is simple, and you want to customize a control that implements the following functions:

1) Achieve a button-like click Effect

2) You can also add a delete small icon at the back to delete the content on this control

3) There is also a response function that can be done after the deletion.

We know that there are many ways to customize a control, and we can directly inherit the view, draw a variety of ui ourselves, or simply inherit existing controls, such as a button that inherits TextView's simple control.

The mention of the button is inherited TextView, and TextView has the concept of compounddrawable, it is clear that we can use the TextView to achieve our function.

Too verbose, let's go ahead with the code.

public class Clearabletextview extends TextView {public interface Ontextclearlistener {public void ontextclear    (Clearabletextview v);    } private Context Mcontext;    Private drawable mdrawableright;    Private Rect mbounds;    Private Ontextclearlistener Montextclearlistener;        Public Clearabletextview (Context context) {super (context);    Initialize (context);        } public Clearabletextview (context context, AttributeSet Attrs) {Super (context, attrs);    Initialize (context);        } private void Initialize (context context) {Mcontext = context;        Mdrawableright = Mcontext.getresources (). getdrawable (R.drawable.ic_delete);        Mdrawableright.setbounds (0, 0, mdrawableright.getminimumwidth (), Mdrawableright.getminimumwidth ());        Setclickable (TRUE);        Setminwidth (120);        Setgravity (gravity.center_vertical);        Setpadding (8, 8, 8, 8);    Setcompounddrawablepadding (8); } @Override public void setcompounddrAwables (drawable left, drawable top, drawable right, drawable bottom) {if (right! = null) {Mdrawableri        Ght = right;    } super.setcompounddrawables (left, top, mdrawableright, bottom); } public boolean ontouchevent (Motionevent event) {if (event.getaction () = = Motionevent.action_up && mDr            Awableright = null) {mbounds = Mdrawableright.getbounds ();            Final int x = (int) event.getx ();            Final int y = (int) event.gety ();                    if (x >= (This.getwidth ()-mbounds.width ()) && x <= (This.getwidth ()-this.getpaddingright ())                && y >= this.getpaddingtop () && y <= (this.getheight ()-This.getpaddingbottom ())) {                Clear ();            Event.setaction (Motionevent.action_cancel);    }} return Super.ontouchevent (event);        } public void Settextclearable (charsequence text) {setText (text); if (text = = NULL | | Text.length () = = 0) {super.setcompounddrawables (null, NULL, NULL, NULL);        } else {super.setcompounddrawables (null, NULL, mdrawableright, NULL);        }} private void Clear () {settextclearable ("");        if (Montextclearlistener! = null) {montextclearlistener.ontextclear (this);    } super.setcompounddrawables (null, NULL, NULL, NULL); } public void Setontextclearlistener (Ontextclearlistener ontextclearlistener) {Montextclearlistener = OnTextCle    Arlistener;        } public void Finalize () throws Throwable {mdrawableright = null;        Mbounds = null;    Super.finalize (); }}

We created a clearabletextview, inherited from TextView, and the key code is as follows:

1) Set Compounddrawables.

We know that in the XML layout, for TextView, we can use Drawableleft, Drawableright, Drawabletop, Drawablebottom and other properties for the TextView settings, respectively, in the left and right icons, As follows:

    <textview        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        android: drawablebottom= "@drawable/ic_delete"        android:drawableleft= "@drawable/ic_delete"        android:drawableright= "@drawable/ic_delete"        android:drawabletop= "@drawable/ic_delete"/>

So in our initialization, we can define a default icon ourselves, or we can get it from the XML layout.

When the corresponding property is set in the XML layout, the function setcompounddrawables is called and we can handle the reset of our mdrawableright.

    @Override public    void Setcompounddrawables (drawable left, drawable top, drawable right, drawable bottom) {        if (ri Ght = null) {            mdrawableright = right;        }        Super.setcompounddrawables (left, top, mdrawableright, bottom);    }

2) The Ontouchevent method must be overloaded.

This is because in the TextView to set the four-sided icon, and does not provide its corresponding Click event, so this requires us to intercept the user's click events, to determine the user's click area, manually to do the corresponding processing, as follows:

    public boolean ontouchevent (Motionevent event) {        if (event.getaction () = = Motionevent.action_up && Mdrawableright = null) {            mbounds = Mdrawableright.getbounds ();            Final int x = (int) event.getx ();            Final int y = (int) event.gety ();            if (x >= (This.getwidth ()-mbounds.width ()) && x <= (This.getwidth ()-this.getpaddingright ())                    &&A mp Y >= this.getpaddingtop () && y <= (this.getheight ()-This.getpaddingbottom ())) {                clear ();                Event.setaction (Motionevent.action_cancel);            }        }        Return Super.ontouchevent (event);    }

Logic is very simple, first to get the rectangle area of the icon, and to get the point at which the user clicked, as long as this point falls within this rectangular region, we can think that the user clicked on this button, our own logic processing, and then set the action of this event to cancel, Then use the system ontouchevent to handle the cancel event.

The clear method in the code is our own logic to deal with, this time, we will have to consider, just do some operations can, or need to interact with the outside?

3) Define an interface that can be implemented externally to trigger when an icon is clicked on an event

    Public interface Ontextclearlistener {public        void Ontextclear (Clearabletextview v);    } ...    private void Clear () {        settextclearable ("");        if (Montextclearlistener! = null) {            montextclearlistener.ontextclear (this);        }        Super.setcompounddrawables (NULL, NULL, NULL, NULL);    }

So, in the clear method, we have to determine if there is an interface that is implemented and passed to the current control, and if so, we call its method.


4) in order to make the text does not exist, the deletion button does not appear, we can define a settextclearable method, which wraps the TextView SetText method, but we will judge according to the parameter content, do not display the delete icon.

    public void settextclearable (charsequence text) {        setText (text);        if (text = = NULL | | text.length () = = 0) {            super.setcompounddrawables (null, NULL, NULL, NULL);        } else {            SUPER.S Etcompounddrawables (null, NULL, mdrawableright, NULL);        }    }

5) Of course, finally, when the button no longer exists in the context, that is, when it is destroyed, we need to clear the corresponding resources, as follows:

    public void Finalize () throws Throwable {        mdrawableright = null;        Mbounds = null;        Super.finalize ();    }

Here, the whole implementation of the explanation, although very simple, but there are places to learn, such as interface definition, a lot of methods of interaction, we can pass the message, but also through the callback function to achieve, specifically to consider the work scenario.

OK, next, just put a control on the outside and look at the effect.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    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=" com.example.clearabletextviewdemo.mainactivity$ Placeholderfragment ">    <com.example.clearabletextviewdemo.clearabletextview        android:id=" @+id/ Ctvtest "        android:layout_width=" wrap_content "        android:layout_height=" wrap_content "        android:text= "@string/hello_world"/></relativelayout>

Code in Mainactivity:

Public View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {View RootView = Inflater.inflate (R.layout.fragment_main, container,false); mctvtest = (Clearabletextview) rootView.findViewById ( R.id.ctvtest); Mctvtest.settextclearable ("Hello World"); Mctvtest.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {mctvtest.settextclearable ("Hello world!");}); Mctvtest.setontextclearlistener (New Ontextclearlistener () {@Overridepublic void ontextclear (Clearabletextview v) { Toast.maketext (Getactivity (), "on Text cleared", Toast.length_short). Show ();}); return Rootview;}}

Finally, of course it is, as follows:


End!

Android Learning Mini Demo (22) TextView with delete button

Related Article

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.