Android知识点总结(十五) Android MVP 简易模型

标签: android    mvp

相关文章:

Android 知识点总结(目录) https://blog.csdn.net/a136447572/article/details/81027701

Mvp简图

一 Activity (UI)

1 实现MvpView接口 ,继承方法
2 创建MvpPresenter2 对象 并new一个对象
3 点击Button调用presenter 方法
4 等待showData() 数据返回

public class MvpActivity extends Activity implements MvpView2 {

    TextView text ;
    ProgressBar progress;
    MvpPresenter2 presenter2 ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mvpactivity);
        text = findViewById(R.id.text);
        progress = findViewById(R.id.progress);
        presenter2 = new MvpPresenter2(this);
    }
    // button 点击事件调用方法
    public void getData(View view){
        presenter2.getData();
    }
    @Override
    public void showDialog() {
        if(progress.getVisibility() == View.GONE){
            progress.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void hideDialog() {
        if(progress.getVisibility() == View.VISIBLE){
            progress.setVisibility(View.GONE);
        }
    }
    @Override
    public void showData(String msg) {
        text.setText("请求成功"+msg);
    }
}

二 MvpView2

public interface MvpView2 {

    void showDialog();
    void hideDialog();
    void showData(String msg);

}

三 MvpPresenter2

1 构造函数传入MvpView 对象
2 presenter getData()方法中调用Model的方法 并在Callback回调中调用view的方法,更新UI数据


public class MvpPresenter2 {
    MvpView2 mvpView2 ;
    public MvpPresenter2(MvpView2 mvpView2) {
        this.mvpView2 = mvpView2;
    }
    public void getData(){
        mvpView2.showDialog();
        new MvpModel2().getData(new MvpCallBack2() {
            @Override
            public void onSuccess(String msg) {
                mvpView2.showData(msg);
            }
            @Override
            public void onEveryRequest() {
                mvpView2.hideDialog();
            }
        });
    }

}

四 MvpModel2

1 模拟求情并调用回调

public class MvpModel2 {
    public  void getData(final MvpCallBack2 callback){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                callback.onSuccess("success");
                callback.onEveryRequest();
            }
        },1000);
    }
}

五 MvpCallBack2

public interface MvpCallBack2  {

    void onSuccess(String msg);
    void onEveryRequest();

}

代码地址

https://download.csdn.net/download/a136447572/10657667

原文链接:加载失败,请重新获取