acefalobi / android-stepper

A library for creating a wizard-like step-through user interface that uses navigation components and menus for displaying steps with advanced customization.
Apache License 2.0
325 stars 38 forks source link

How to browse stepper from inside a fragment #20

Closed mspnr closed 3 years ago

mspnr commented 3 years ago

Here is a question regarding your example of using the stepper.

In your example with numbered tabs stepper, the only way to go to next step is by clicking the button in the activity itself: https://github.com/acefalobi/android-stepper/blob/9859d114536e1a7015beb5fc1b77cefa1fa4955a/app/src/main/java/com/aceinteract/android/stepper/presentation/samples/NumberedTabStepperActivity.kt#L60

I would like to build some buttons for going back and forth in the fragment itself (because some processing logic is related to the steps).

What would be your advice to trigger jump between steps from inside the fragment?

acefalobi commented 3 years ago

An easy way to get this done would be to use a shared viewmodel with an observer.

Something like this in your viewmodel

private val _stepChange = MutableStateFlow(StepChangeType.IDLE)
val stepChange: StateFlow<StepChangeType>get() = _stepChange

fun goToNextStep() {
    _stepChange.value = StepChangeType.NEXT_STEP
}

fun goToPreviousStep() {
    _stepChange.value = StepChangeType.PREVIOUS_STEP
}

In your activity, you can then collect the flow.

viewModel.stepChange.onEach {
    when (it.type) {
        StepChangeType.NEXT_STEP -> stepper.goToNextStep()                    
        StepChangeType.PREVIOUS_STEP -> stepper.goToPreviousStep()
    }
}.launchIn(lifecycleScope)

StepChange.kt

enum class StepChangeType { IDLE, NEXT_STEP, PREVIOUS_STEP }

You could also use LiveData for this.

acefalobi commented 3 years ago

Closing this because it seems it has been answered