View -> Presenter -> Model -> Presenter -> View
View 包含 xml 布局文件和 Activity 或 Fragment,并与 Presenter 通信
public class MainActivity extends AppCompatActivity implements IContract.View{
private Button mBtn;
// 和 Presenter 通信
private IContract.Presenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPresenter=new Presenter(this);
mBtn=(Button)findViewById(R.id.button);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 通过 mPresenter 调用
mPresenter.loadClickString();
}
});
}
@Override
protected void onStart() {
super.onStart();
mPresenter.start(); // Presenter的初始化
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.destroy(); //断开 Presenter 和 View 的连接
}
/**
* 实现 接口 IContract.View
* @param s
*/
@Override
public void updateBtnText(String s) {
mBtn.setText(s);
}
@Override
public void showToast(String s) {
Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
}
}
Presenter 与 View 和 Model 通信
public class Presenter implements IContract.Presenter {
// 和 View 通信
private IContract.View mView;
public Presenter(IContract.View view){
mView=view;
}
/**
* 实现 接口 IContract.Presenter
*/
@Override
public void start() {
String s=ModelDataSource.ins().getBtnText();
mView.updateBtnText(s);
}
@Override
public void loadClickString() {
String s=ModelDataSource.ins().getBtnClicked();
mView.showToast(s);
}
@Override
public void destroy() {
mView = null;
}
}
Model 单例,被 Presenter 调用
public class ModelDataSource {
private static ModelDataSource mInstance;
public static ModelDataSource ins(){
if(mInstance==null){
synchronized (ModelDataSource.class){
if(mInstance==null){
mInstance=new ModelDataSource();
}
}
}
return mInstance;
}
public String getBtnText(){
return " from ModelDataSource ";
}
public String getBtnClicked(){
return " from ModelDataSource Hello mVP ";
}
}
参考博客 浅谈Android中的MVP
网友评论