0

我创建了一个 Activity 和 ViewModel 来收集 Stateflow 以切换视图。

这是我的活动课

@AndroidEntryPoint 类 LoggingActivity : AppCompatActivity() {

private var _bind : ActivityLoggingBinding? = null

private val bind : ActivityLoggingBinding get() = _bind!!

private lateinit var email : String

private val loggingViewModel : LoggingViewModel by viewModels()



override fun onCreate(savedInstanceState : Bundle?) {
    super.onCreate(savedInstanceState)
    _bind = ActivityLoggingBinding.inflate(layoutInflater)
    setContentView(bind.root)

    getExtras()
    collectToggleViewFlow()

    bind.btnSave.setOnClickListener {
        loggingViewModel.toggleView()
    }

}

private fun getExtras() {
    email = intent.extras?.getString("email")!!

    when (email) {
        "No User" -> loggingViewModel.toggleView()
        else -> loggingViewModel.toggleView()
    }
}

private fun collectToggleViewFlow() {
    lifecycleScope.launchWhenStarted {
        loggingViewModel.toggleFlow.collect{
            when(it){
                is LoggingViewModel.ToggleView.SignUp -> {
                    bind.inputName.visible()
                    bind.inputPhoneNo.visible()
                }
                is LoggingViewModel.ToggleView.SignIn -> {
                    bind.inputName.inVisible()
                    bind.inputPhoneNo.inVisible()
                }
                is LoggingViewModel.ToggleView.Nothing -> Unit
            }
        }
    }
 }
}

这是我的 ViewModel 类

@HiltViewModel 类 LoggingViewModel @Inject 构造函数(private val firebaseAuthRepo : FirebaseAuthRepo,) : ViewModel() {

private val _toggleFlow : MutableStateFlow<ToggleView> = MutableStateFlow(ToggleView.Nothing)

val toggleFlow : StateFlow<ToggleView> get() = _toggleFlow


fun toggleView() {
    when (toggleFlow.value) {
        ToggleView.SignIn -> _toggleFlow.value = ToggleView.SignUp
        ToggleView.SignUp -> _toggleFlow.value = ToggleView.SignIn
        else -> _toggleFlow.value = ToggleView.SignIn
    }
}


sealed class ToggleView {
    object Nothing : ToggleView()
    object SignIn : ToggleView()
    object SignUp : ToggleView()
}

}

我创建了按钮单击事件以在视图可见性之间切换。当我单击 SIGNUP 按钮时,它工作正常。

人像模式 image1 | 通过单击按钮切换视图

人像模式 image2 | 通过单击按钮切换视图

当我将手机旋转到横向时,如果没有 buttonclick 事件,它会自动切换视图,我不知道为什么?

横向模式图像 | 自动切换视图

4

0 回答 0