欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

Jetpack之Lifecycle+MVP结合

程序员文章站 2022-06-18 13:50:51
Lifecycle+mvp关于Lifecycle mvp 是什么 不多说Lifecycle+mvp 结合的作用?主要用于其他的类能够监听 Activity Fragemnt的生命周期 ,防止内存泄露等等....Lifecycle代码import androidx.lifecycle.Lifecycle;import androidx.lifecycle.LifecycleObserver;import androidx.lifecycle.LifecycleOwner;....

Lifecycle+mvp

关于Lifecycle mvp 是什么 不多说

代码地址

Lifecycle+mvp 结合的作用?

主要用于其他的类能够监听 Activity Fragemnt的生命周期 ,防止内存泄露等等....

Lifecycle代码


import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

public interface BaseLifecycleObserver extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStart(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestory(LifecycleOwner owner);
}

BasePresenter继承BaseLifecycleObserver 

package com.example.mvpdemo.base;

import com.example.mvpdemo.view.LoginView;

public interface BasePresenter<V extends BaseView> extends BaseLifecycleObserver {
    LoginView attchViews(V v);

}

  BaseActivity添加getLifecycle().addObserver(this.presenter); 这样就可以监听

 

package com.example.mvpdemo.base;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

/**
 * 抽象出绑定和解绑
 * 兼容多个 Ac 采取泛型
 *
 *
 */
public abstract class BaseActivity<V extends BaseView,P extends BasePresenter<V>> extends AppCompatActivity {

    private  V view;
    private P presenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         if(this.presenter==null){
             this.presenter=createPresenter();
         }
         if(this.view==null){
             this.view=createView();
         }
         if(this.presenter!=null&&this.view!=null){
             this.presenter.attchViews(this.view);
             getLifecycle().addObserver(this.presenter);
         }
    }

    protected abstract V createView();

    protected abstract P createPresenter();
    public P getPresenter(){
        return  this.presenter;
    }


}

 

本文地址:https://blog.csdn.net/xueshao110/article/details/108146029

相关标签: Android