Bean Manager View
manager负责网络请求,继承 java.util.Observable
主要内容:
public class RequestManger extends Observable { private static ConsultListManger mManager; private String TAG = this.getClass().getSimpleName(); private ConsultListManger() { } public synchronized static ConsultListManger getInstance() { if (mManager == null) { mManager = new RequestManger (); } return mManager; }
//网络请求的方法 public void request() {
//在网络请求出现结果后调用
setChanged();
notifyObservers(informationListBean);
如:
request.setHttpListener(new HttpListener<String>() { @Override public void onSuccess(String s, Response<String> response) { super.onSuccess(s, response); setChanged(); notifyObservers(informationListBean); } } @Override public void onFailure(HttpException e, Response<String> response) { super.onFailure(e, response); setChanged(); notifyObservers("网络请求失败!"); } });
} }
View是activity或者fragment,需要实现 java.util.Observer,实现Observer的update()方法。
主要内容:
public class Fragment extends Fragment implements Observer{
requestManager = RequestManager.getInstance();
requestManager.addObserver(this);
requestManager.request();
........
@Override public void update(Observable o, Object arg) { if (o instanceof RequestManager) { if (arg instanceof Bean) { setData(((Bean) arg)); } } }
private void setData(Bean bean){
//设置UI
}
@Override
protected void onDestroy() {
super.onDestroy();
requestManager.deleteObserver(this);
}
}
在activity的onDestory()中要删除observe,否则会出现问题。