LifecycleOwner を取得するためのプレゼンテーションとダイアログの 2 画面差分表示

1. プレゼンテーションはダイアログに基づいているため、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;
    }
}

注: プレゼンテーションはダイアログに基づいているため、これはダイアログにも使用できます (コンストラクターのプレゼンテーション タイプをダイアログ タイプに変更するだけです)。

2.用途

以下に示すように、使用する必要がある場所で new PresentationLifeCycleOwner(this) を使用して直接取得するだけです。

mMutableLiveData.observe(new PresentationLifeCycleOwner(this), ver -> {...})

おすすめ

転載: blog.csdn.net/savet/article/details/131168426