Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android how to make listener to a custom variable?

i've seen this thread : How to implement a listener about implement listeners.

its actually pretty simple but i don't get how exactly its done and how to implement in my own code.

i have this static variable variable: AppLoader.isInternetOn. i want to build a listener which will listen to this variable changes and update a TextView.

should i do this: ?

build an interface:

public interface InternetStateListener {
     public void onStateChange();
}

run it in my activity:

public class MyActivity extends Activity {
private InternetStateListener mListener;

setTheListener(this);

public void setTheListener(InternetStateListener listen) {
    mListener = listen;
}

private void onStateChange() {
    if (mListener != null) {
       if (AppLoader.isInternetOn)
        text.setText("on")
       else
        text.setText("off")
    }
  }
}
like image 237
Asaf Nevo Avatar asked Mar 26 '12 20:03

Asaf Nevo


1 Answers

Your Activity does nothing special, just register itself (since the interface is implemented directly in the class) with the Other class that provides the listener.

public class MyActivity extends Activity implements InternetManager.Listener {

    private TextView mText;
    private InternetManager mInetMgr;

    /* called just like onCreate at some point in time */ 
    public void onStateChange(boolean state) {
        if (state) {
            mText.setText("on");
        } else {
            mText.setText("off");
        }
    }

    public void onCreate() {
        mInetMgr = new InternetManager();
        mInetMgr.registerListener(this);
        mInetMgr.doYourWork();
    }
}

The other class has to do pretty much all the work. Besides that it has to handle the registration of listeners it has to call the onStateChange method once something happend.

public class InternetManager {
    // all the listener stuff below
    public interface Listener {
        public void onStateChange(boolean state);
    }

    private Listener mListener = null;
    public void registerListener (Listener listener) {
        mListener = listener;
    }

    // -----------------------------
    // the part that this class does

    private boolean isInternetOn = false;
    public void doYourWork() {
        // do things here
        // at some point
        isInternetOn = true;
        // now notify if someone is interested.
        if (mListener != null)
            mListener.onStateChange(isInternetOn);
    }
}
like image 90
zapl Avatar answered Sep 22 '22 05:09

zapl