简体   繁体   中英

Call a listener from another class

In my android project's main class i've got about six listener, with this structure:

temp.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable arg0) {

            }

            public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) { }
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

        });

But it's a bit disorganized... the goal i'd like to do, is create a general class, called, for example, TextBox, which contains all its listeners. Same thing for the buttons, with its listeners. Do you understand? How can I do this?

With this system I can call a method in this way:

temp.addTextChangedListener(TextBox.temp())
test.addTextChangedListener(TextBox.test())

If I've explained myself badly just tell me. Thanks.

Define the class with all the listeners:

Class Listeners {
    public class Listener1 extends EditView.TextChangedListener{

    ...

    }
}

Then instantiate them as needed:

temp.addTextChangedListener(new Listeners.Listener1());

Inside the class you are planning to implement (let's say TextBox), create as many methods as you need, the should return for example an anonymous implementation in this case of the TextWatcher interface take a look:

public class TextBox{
  public static TextWatcher temp(){
    return new TextWatcher() {
            public void afterTextChanged(Editable arg0) {

            }
            public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) { }
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
        };
  }
}

using it:

temp.addTextChangedListener(TextBox.temp());

I don't like this approach but still hope it helps..., I recommend you to read this articles:

http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

http://docs.oracle.com/javase/tutorial/uiswing/events/

They would give you some ideas of common design patterns when dealing with events and listeners....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM