流程:
1.Model
定义Model层的接口IModel
Model层接口---实现该接口的类负责实际的获取数据操作,如数据库读取、网络加载
创建Model实体类实现IModel接口,并覆写数据获取方法。
public interfaceIModel{
void getData(Model.LoadDataCallback callback);
}
public classModelimplementsIModel{
void getData(Model.LoadDataCallback callback){
//实现获取数据
callback.success(data);
}
}
public interfaceLoadDataCallback{ void success(String taskId);
void failure();
}
2 view 层
定义IView接口(View层接口---执行各种UI操作,定义的方法主要是给Presenter中来调用的)
然后创建View实体类实现IView接口,并覆写UI操作方法。
public interfaceIView{ void showLoadingProgress(String message);
void showData(String text);
}
public class ViewActivity extends Activity implements IView {
private Button mBtnShowToast;
private TextView mText;
private MyHandler mHandler = new MyHandler(ViewActivity.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mvp);
mBtnShowToast = (Button) findViewById(R.id.btn_show_toast);
mText = (TextView) findViewById(R.id.text);
mBtnShowToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public void showLoadingProgress(final String message) {
mHandler.post(new Runnable() {
@Override
public void run() {
mText.setText(message);
}
});
}
@Override
public void showData(final String text) {
mHandler.post(new Runnable() {
@Override
public void run() {
mText.setText(text);
}
});
}
}
}
3、定义IPresenter接口
/**
* Presenter层接口---控制Model层的数据操作及调用View层的UI操作来完成“中间人”工作
*/
public interface IPresenter {
void loadData();
}
4、View中实例化Presenter,通过Presenter来处理业务逻辑。最终达到,View只负责UI操作,Model只负责数据,Presenter负责链接二者的目的。
View层完整代码
/**
* 实现IView接口并实现各种UI操作的方法(其他的业务逻辑在Presenter中进行操作)
*/
public class ViewActivity extends Activity implements IView {
private Button mBtnShowToast;
private TextView mText;
private MyHandler mHandler = new MyHandler(ViewActivity.this);
private IPresenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mvp);
//实例化Presenter,并将实现了IView接口的类传入进去
mPresenter = new Presenter(ViewActivity.this);
mBtnShowToast = (Button) findViewById(R.id.btn_show_toast);
mText = (TextView) findViewById(R.id.text);
mBtnShowToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//通过Presenter来实现业务逻辑操作,View层只负责UI相关操作
mPresenter.loadData();
}
});
}
@Override
public void showLoadingProgress(final String message) {
mHandler.post(new Runnable() {
@Override
public void run() {
mText.setText(message);
}
});
}
@Override
public void showData(final String text) {
mHandler.post(new Runnable() {
@Override
public void run() {
mText.setText(text);
}
});
}
private class MyHandler extends Handler {
//弱引用,防止内存泄露
WeakReference
public MyHandler(ViewActivity activity) {
this.weakReference = new WeakReference
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
weakReference.get().mText.setText(msg.what);
break;
}
}
}
}