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?