Search code examples
androidonclicklistenertextwatcher

TextWatchers, OnClickListeners and such


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.


Solution

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