Home > DeveloperSection > Forums > TextWatchers, OnClickListeners in android
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    November-06-2014 10:45 PM

 Android Textwatcher  OnClicklistener 
Ratings:


 1 Reply(s)
 691  View(s)
Rate this:

Just wondering if there is any best practice on the use of TextWatchers, OnClickListeners and such like with regards to how you put them in code.

Would you do the following:

textBox.addTextChangedListener(new TextWatcher()

{

    public void afterTextChanged(Editable s)

    {              

         // some code here

    }

 

    public void beforeTextChanged(CharSequence s, int start, int count, int after)

    {

         // and/or here

    }

 

    public void onTextChanged(CharSequence s, int start, int before, int count)

    {

         // and/or even here

    }

 });

Or would it be best to have the TextWatcher etc as a variable and call it like:

textBox.addTextChangedListener(myTextWatcher);

I understand the second would be far better for reusability but was curious about if there is only one instance of the, in this example, TextWatcher.



Barbara Jones

Total Post:13

Points:91
Posted on    November-07-2014 1:23 AM

I think there is the other option that is implementing the interface on your main class and then having something like this:


textBox.addTextChangedListener(myTextWatcher);

In total there are 3 options and I use 3 of them.


If the TextWatcher or the onClickListener need some configuration (eg. id or row number) and to be used multiple times, I create my own class and does something like this:


textBox1.addTextChangedListener(new MyTextWatcher(1, "Some Text"));

textBox2.addTextChangedListener(new MyTextWatcher(2, "Some Other Text"));

textBox3.addTextChangedListener(new MyTextWatcher(3, "Some Text 4"));

Other than that if it is a one time thing and is small, I go like this:


mButton.setOnClickListener(new OnClickListener() {

    ....

});

And I also use ButterKnife a lot. As far as I know it does not have any annotation for TextWatchers but it has onClickListener, onItemClickListener, onItemLongClickListener etc. And you can use one function for multiple Views using annotations.


Modified On Nov-07-2014 01:24:10 AM

Don't want to miss updates? Please click the below button!

Follow MindStick