我见过这个帖子:如何实现一个关于实现监听器的监听器.
它实际上非常简单,但我不知道它是如何完成的以及如何在我自己的代码中实现.
我有这个静态变量变量:AppLoader.isInternetOn.我想构建一个监听器,它将监听这个变量并更新TextView.
我应该这样做吗?
构建一个接口:
public interface InternetStateListener {
public void onStateChange();
}
Run Code Online (Sandbox Code Playgroud)
在我的活动中运行它:
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")
}
}
}
Run Code Online (Sandbox Code Playgroud)
zap*_*apl 25
你的Activity没有什么特别的,只是通过提供监听器的Other类来注册自己(因为接口是直接在类中实现的).
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();
}
}
Run Code Online (Sandbox Code Playgroud)
另一个班级必须完成所有的工作.除此之外,它必须处理监听器的注册,onStateChange一旦发生某事,它必须调用该方法.
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);
}
}
Run Code Online (Sandbox Code Playgroud)