Jetpack 库 ---- Activity

上次库更新时间

2020 年 1 月 22 日

当前稳定版

| 1.1.0 |

API 参考文档

androidx.activity

Interfaces-- OnBackPressedDispatcherOwner

用途:处理系统后退按钮
举例:可以在fragment里用该方法处理系统返回键

 //定义变量
private var backListener: OnBackPressedCallback? = null
private var backListener2: OnBackPressedCallback? = null

//初始化
backListener = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        logI("点击事件1")
        backListener?.isEnabled = false
        backListener2?.isEnabled = true
    }
}

backListener2 = object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        logI("点击事件2")
        backListener?.isEnabled = true
        backListener2?.isEnabled = false
    }
}

//fragment新增callback
requireActivity().onBackPressedDispatcher.addCallback(backListener2!!)
requireActivity().onBackPressedDispatcher.addCallback(backListener!!)

tips:
1、addCallback方法是把callback添加到一个mOnBackPressedCallbacks的ArrayDeque里,触发返回键的时候会执行最近被添加的且isEnabled = true的 callback方法。

    //以下是源码
    @MainThread
    public void onBackPressed() {
        Iterator iterator =
                mOnBackPressedCallbacks.descendingIterator();
        while (iterator.hasNext()) {
            OnBackPressedCallback callback = iterator.next();
            if (callback.isEnabled()) {
                callback.handleOnBackPressed();
                return;
            }
        }
        if (mFallbackOnBackPressed != null) {
            mFallbackOnBackPressed.run();
        }
    }

2、OnBackPressedCallback有如下方法可以调用

//获取callback开启状态
logI("${backListener?.isEnabled}")
//设置callback开启状态
backListener?.isEnabled = false
//触发callback
backListener?.handleOnBackPressed()
//移除callback
backListener?.remove()

你可能感兴趣的:(Jetpack 库 ---- Activity)