MVP 简单介绍
M(model)负责数据的请求,解析,过滤等数据操作
V(View)负责图示部分展示,图示事件处理,Activity,Fragment,Dialog,ViewGroup等呈现视图的组件都可以承担该角色
P(presenter)是View和Model交互的桥梁。
直接上代码
Activity
public class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements MvpView {
public P mPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initPresenter();
}
@Override
public void showToast(String title, int des) {
Toast.makeText(this, title, des).show();
}
private void initPresenter() {
Class<P> tClass = (Class<P>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
try {
this.mPresenter = tClass.newInstance();
if (null != mPresenter) {
mPresenter.attachView(this);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public P getPersenter() {
return mPresenter;
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mPresenter) {
mPresenter.detachView();
}
}
}
public class WeatherActivity extends BaseActivity<PersenterWeather> implements IUIWeather, View.OnClickListener {
private TextView mTv1;
private TextView mTv2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
mTv1 = findViewById(R.id.TV1);
mTv2 = findViewById(R.id.TV2);
findViewById(R.id.BT1).setOnClickListener(this);
}
@Override
public void updateWeather(WeatherData weather) {
mTv1.setText("城市:" + weather.getData().getCity());
mTv2.setText("温度:" + weather.getData().getWendu());
}
@Override
public void onClick(View v) {
mPresenter.getWeather();
}
}
Presenter
public interface Presenter<V extends MvpView> {
void attachView(V mMvpView);
void detachView();
V getMvpView();
}
public class BasePresenter<V extends MvpView> implements Presenter<V> {
private V mMvpView;
@Override
public void attachView(V mMvpView) {
this.mMvpView = mMvpView;
}
@Override
public void detachView() {
mMvpView = null;
}
@Override
public V getMvpView() {
return mMvpView;
}
}
public class PersenterWeather extends BasePresenter<IUIWeather> {
public void getWeather() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.apiopen.top/").addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();
final Api api = retrofit.create(Api.class);
Observable<WeatherData> observable = api.getWeather("杭州");
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<WeatherData>() {
@Override
public void accept(WeatherData weatherData) throws Exception {
getMvpView().updateWeather(weatherData);
getMvpView().showToast(new Gson().toJson(weatherData), Toast.LENGTH_LONG);
}
});
}
}
MvpView
public interface MvpView {
void showToast(String title, int des);
}
public interface IUIWeather extends MvpView {
void updateWeather(WeatherData weather);
}