android MVP 简单DEMO

最近新入职一家公司发现架构用的是mvp但写的并不好,尤其是在将页面下的所有接口反回的数据都回调在activity里完全违背了mvp的解耦原则,所以自己写了一个就当练习了还没有应用到正式项目中  如果大家看看发现问题请指出勿喷 我也是希望能帮到大家 。

BaseActivity 

import android.app.Activity;
import android.os.Bundle;

import com.example.mvp.presenter.BasePresenter;

import java.lang.reflect.ParameterizedType;


public abstract class BaseActivity extends Activity {
    T presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        try {
            ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class clazz = (Class) ptype.getActualTypeArguments()[0];
            presenter = (T) clazz.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        presenter.setHold(this);
        init();
        presenter.initData();
    }

    public abstract void init();

    public abstract int getLayoutId();
}

 BasePresenter

import com.example.mvp.BaseActivity;

public class BasePresenter {

    public T hold;

    public void setHold(T hold) {
        this.hold = hold;
    }
    public void initData(){};
}

MainPresenter  

import android.view.View;

import com.example.mvp.MainActivity;

public class MainPresenter extends BasePresenter {

    public String test;

    public void iniData2() {

    }

    @Override
    public void initData() {
        hold.hello.setText("wocaowonadaole");
        hold.hello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                hold.hello.setText("test");
            }
        });
    }
}

 MainActivity 

import android.widget.TextView;

import com.example.mvp.presenter.MainPresenter;

public class MainActivity extends BaseActivity {

    public TextView hello;
    @Override
    public void init() {
        hello = findViewById(R.id.tv_hello);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }
}

 

你可能感兴趣的:(android,MVP)