Preserving Bottom sheet fragment state and visibility on orientation change without FragmentManager

I was assigned to add support at my new job for preserving BottomSheet state & visibility on orientation change, but I’m having a hard time retaining any of those when the Activity is re-created.

All sheet classes are based on the base one:

abstract class BaseSheetFragment(@LayoutRes override val layoutRes: Int) : BaseFragment() {
        protected var behavior: BottomSheetBehavior<*>? = null
        protected var bgMask: View? = null
        protected var onDismiss: () -> Unit = {}
        private val defaultViewModel: DefaultViewModel by activityViewModel()
        abstract val classTag: String

    override fun initViews() {
        behavior?.skipCollapsed = true
        val animator: ObjectAnimator = ObjectAnimator.ofPropertyValuesHolder(
            bgMask,
            PropertyValuesHolder.ofInt("alpha", 0, 255)
        )
        animator.target = bgMask
        animator.duration = 75
        animator.start()
        Handler(Looper.getMainLooper()).postDelayed({
            behavior?.state = BottomSheetBehavior.STATE_EXPANDED
        }, 75)
        behavior?.peekHeight = 0
        behavior?.isHideable = false
        behavior?.addBottomSheetCallback(object : BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (newState) {
                    BottomSheetBehavior.STATE_COLLAPSED, BottomSheetBehavior.STATE_HIDDEN -> {
                        defaultViewModel.dismissSheets()
                    }

                    else -> Unit
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })

        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner, object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    dismiss()
                }
            }
        )
        bgMask?.setOnClickListener { dismiss() }
    }

    fun dismiss() {
        onDismiss()
        behavior?.state = BottomSheetBehavior.STATE_COLLAPSED
    }
}

Now, let’s see an example. The app displays its MainActivity which creates FragmentA, now upon navigating to FragmentA, BottomSheetA is displayed collapsed. Upon expanding it, clicking the “options” button loads BottomSheetB on top of everything. Changing orientation at this point, dismisses BottomSheetB and collapses BottomSheetA basically reseting the state for everything.

The desired behavior would be to keep BottomSheetA expanded and still show BottomSheetB on top (with its state, etc.).

The developer who was in charge of the code so far, creates instances of fragments this way:

class BottomSheetB : BaseSheetFragment(R.layout.core_sheet_picker) {
    override val classTag: String = "PickerDialog"

private val binding: CoreSheetPickerBinding by viewBinding()
private val viewModel: PickerViewModel by viewModel()

private var initState: UIState = UIState()
private var initCallback: (Int) -> Unit = {}
private var initValues: List<ValueMapper> = listOf()

private var initPickerValue: Boolean = true

override fun initViews() {
    behavior = BottomSheetBehavior.from(binding.clContent)
    bgMask = binding.vBgMask
    super.initViews()
    viewModel.setup(initState, initCallback, initValues)
    with(binding) {
        btnClose.setOnClickListener { viewModel.dismiss() }
        btnDone.setOnClickListener { viewModel.onConfirmClick() }

        val values = viewModel.values
        picker.maxValue = max(values.size - 1, 0)
        picker.minValue = 0
        picker.displayedValues = values.map { it.title }.toTypedArray()
        picker.descendantFocusability = NumberPicker.FOCUS_BLOCK_DESCENDANTS
        picker.wrapSelectorWheel = true

        picker.setOnValueChangedListener { numberPicker, i, i2 ->
            viewModel.onValueChange(viewModel.values[i2].value)
        }
    }

}

override fun bindViews() {
    super.bindViews()
    viewModel.uiEvents.collectWithLifecycle(viewLifecycleOwner) { event ->
        when (event) {
            is UIEvent.Dismiss -> dismiss()
        }
    }
    viewModel.uiState.collectWithLifecycle(viewLifecycleOwner) { state ->
        with(binding) {
            tvTitle.text = state.title
            if (initPickerValue) {
                picker.value =
                    viewModel.values.indexOfFirst { value -> value.value == state.selectedValue }
                initPickerValue = false
            }
        }
    }
}

companion object {
    fun newInstance(
        values: List<ValueMapper>,
        selectedValue: Int,
        callback: (Int) -> Unit,
        title: String
    ): PickerSheetFragment = PickerSheetFragment().apply {
        initState = UIState(title, selectedValue)
        initCallback = callback
        initValues = values
    }

}
}

And this is how the BottomSheetB is instantiated and shown from within FragmentA which already displays BottomSheetA:

private fun selectFlightHeight(height: Double) {
    val values = IntRange(3, 99).map { i ->
        val (factor: Int, resId: Int) = if (UserService.units.isImperial()) {
            Pair(20, CoreR.string.data)
        } else {
            Pair(5, CoreR.string.data)
        }

        ValueMapper(
            getString(resId, i * factor + factor), i * factor + factor
        )
    }
    val pickerFragment = BottomSheetB.newInstance(
        values = values,
        title = getString(R.string.data),
        callback = { viewModel.onHeightSelected(it) },
        selectedValue = height.toInt(),
    )

    defaultViewModel.showSheet(pickerFragment)
}

As you can see, they pass around arguments via the constructor instead of navigation arguments as well as callbacks. My issue is that I cannot see how the logic can be adjusted as is (without a rewrite of these parts) in order to implement state retention.

For example, won’t callbacks be invalidated basically upon Activity re-creation, since the original reference will be lost? Will storing all the relevant state (lists, strings, callbacks, etc.) in the BottomSheetB viewmodel in the onSaveInstanceState of FragmentA and recovering it work?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật