1.由于Presentation是基于Dialog的,所以只能通过实现自定义LifecycleOwner
import android.app.Presentation;
import android.content.DialogInterface;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
/**
* Presentation用生命感知组件
* <br/>
* 示例: mMutableLiveData.observe(new PresentationLifeCycleOwner(this), ver -> {...})
*
* @author savet
* @author 2023/6/12
*/
public class PresentationLifeCycleOwner implements LifecycleOwner {
private DialogInterface.OnDismissListener proxyOnDismissListener;
private DialogInterface.OnShowListener proxyOnShowListener;
private final LifecycleRegistry lifecycleRegistry;
/**
* 构建一个Presentation的LifeCycleOwner<br/>
* 注意: <br/>
* 由于生命感知是通过setOnShowListener和setOnDismissListener来自动设置的 <br/>
* 所以,如果需要监听这两个状态,则需要通过{@link PresentationLifeCycleOwner#setProxyOnDismissListener}和
* {@link PresentationLifeCycleOwner#setProxyOnShowListener}来代理监听
*
* @param presentation presentation
*/
public PresentationLifeCycleOwner(Presentation presentation) {
// 创建
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
// 显示
presentation.setOnShowListener(dialog -> {
lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
if (proxyOnShowListener != null) {
proxyOnShowListener.onShow(dialog);
}
});
// 摧毁
presentation.setOnDismissListener(dialog -> {
lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
if (proxyOnDismissListener != null) {
proxyOnDismissListener.onDismiss(dialog);
}
});
}
/**
* 代理OnDismissListener
*
* @param proxyOnDismissListener OnDismissListener
*/
public void setProxyOnDismissListener(DialogInterface.OnDismissListener proxyOnDismissListener) {
this.proxyOnDismissListener = proxyOnDismissListener;
}
/**
* 代理OnShowListener
*
* @param proxyOnShowListener OnShowListener
*/
public void setProxyOnShowListener(DialogInterface.OnShowListener proxyOnShowListener) {
this.proxyOnShowListener = proxyOnShowListener;
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
注:由于Presentation是基于Dialog的,所以这个也可以用于Dialog(把构造函数的Presentation类型修改为Dialog类型即可)
2.使用
在需要使用的地方直接new PresentationLifeCycleOwner(this)来获得即可,如下所示:
mMutableLiveData.observe(new PresentationLifeCycleOwner(this), ver -> {...})