Android开发记录-MVP模式
2019-08-15 本文已影响0人
LH_1994
Android开发记录主要记录一些实用的开发模式,自定义控件视图和一些第三方的引用。也省去记不住的繁琐..
好了!本篇主要为了快速搭建一个MVP案例,实用为主!!至于MVP模式介绍、MVC模式介绍这里就不啰嗦了,有好多大神详细的分析,这里只放个MVP模式工作图啦。
mvp.png
MVP模式的核心思想:
MVP把Activity中的UI逻辑抽象成View接口,把业务逻辑抽象成Presenter接口,Model类还是原来的Model。
接下来
我们以最简单的Splash页跳转到MainActivity为一个例子,以下是代码目录,个人喜好加借鉴,也可以根据model,view,presenter来做区分!
目录.png
第一步
SplashViewInterface
public interface SplashViewInterface {
void jumpToMainActivity();
}
第二步
SplashPresenter ,做一个简单的2秒跳转
public class SplashPresenter implements SplashInteractor.OnFinishedListener {
private SplashViewInterface splashViewInterface;
private SplashInteractor splashInteractor;
SplashPresenter(SplashViewInterface splashViewInterface, SplashInteractor splashInteractor) {
this.splashViewInterface = splashViewInterface;
this.splashInteractor = splashInteractor;
}
void onCreate() {
//延迟两秒跳转
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (splashViewInterface != null) {
splashViewInterface.jumpToMainActivity();
}
}
}, 2000);
}
void onDestroy() {
splashViewInterface = null;
}
@Override
public void onFinished(String callString) {
if (splashViewInterface != null) {
}
}
}
第三步
SplashInteractor
public class SplashInteractor {
private String TAG = "SplashInteractor";
interface OnFinishedListener {
void onFinished(String callString);
}
//可做些http请求,返回接口如上
}
第四步
SplashActivity
public class SplashActivity extends AppCompatActivity implements SplashViewInterface {
private final String TAG = this.getClass().getSimpleName();
private SplashPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
presenter = new SplashPresenter(this, new SplashInteractor());
presenter.onCreate();
}
@Override
public void jumpToMainActivity() {
//跳转到主界面
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDestroy();
}
}
结尾
当你体会到回头查看Activity内代码过长过多,然后发现不用在Activiy里写一堆乱七八糟的逻辑以后,你就会发现它的好处了!