android how to make listener to a custom variable?

后端 未结 2 1298
無奈伤痛
無奈伤痛 2021-02-01 10:26

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

2条回答
  •  伪装坚强ぢ
    2021-02-01 10:51

    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);
        }
    }
    

提交回复
热议问题