Android開發(fā)記錄-MVP模式

Android開發(fā)記錄主要記錄一些實(shí)用的開發(fā)模式,自定義控件視圖和一些第三方的引用。也省去記不住的繁瑣..

好了!本篇主要為了快速搭建一個(gè)MVP案例,實(shí)用為主?。≈劣贛VP模式介紹、MVC模式介紹這里就不啰嗦了,有好多大神詳細(xì)的分析,這里只放個(gè)MVP模式工作圖啦。


mvp.png

MVP模式的核心思想:

MVP把Activity中的UI邏輯抽象成View接口,把業(yè)務(wù)邏輯抽象成Presenter接口,Model類還是原來的Model。

接下來

我們以最簡單的Splash頁跳轉(zhuǎn)到MainActivity為一個(gè)例子,以下是代碼目錄,個(gè)人喜好加借鑒,也可以根據(jù)model,view,presenter來做區(qū)分!


目錄.png

第一步

SplashViewInterface

public interface SplashViewInterface {
    void jumpToMainActivity();
}

第二步

SplashPresenter ,做一個(gè)簡單的2秒跳轉(zhuǎn)

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() {
        //延遲兩秒跳轉(zhuǎn)
        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() {
        //跳轉(zhuǎn)到主界面
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

}

結(jié)尾

當(dāng)你體會到回頭查看Activity內(nèi)代碼過長過多,然后發(fā)現(xiàn)不用在Activiy里寫一堆亂七八糟的邏輯以后,你就會發(fā)現(xiàn)它的好處了!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容