簡體   English   中英

如何在 jetpack compose 中為一個文本字段使用共享視圖模型?

[英]How can I use shared view model in jetpack compose for one textfield?

我有一個用於用戶電話號碼的文本字段,我想將此電話號碼用於將用戶注冊到Firestore並將其用於移動身份驗證,所以我有兩個 ViewModel 並且我想將ShareViewModel用於此號碼文本字段,是否可以在 android jetpack compose 中使用它?

AuthViewModel

    @HiltViewModel
    class AuthenticationViewModel @Inject constructor(
    
        val auth: FirebaseAuth
    
        ) : ViewModel() {
    
  .....
    
    
    
        }

RegisterViewModel

   @HiltViewModel
    class RegisterViewModel @Inject constructor(
        val db: FirebaseFirestore,
        val auth: FirebaseAuth,
   
    
    ) : ViewModel() {
    
 
      ......
        }


    

RegisterScreen

    @OptIn(ExperimentalComposeUiApi::class)
    @Composable
    fun RegisterScreen(
    
        navController: NavController,
        model: RegisterViewModel
    
    ) {
    
       val phoneNumberState = remember { mutableStateOf("") }
    
        OutlinedTextField(
                value = phoneNumberState.value,
                colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = white,
                    focusedIndicatorColor = Grey,
                    unfocusedIndicatorColor = Grey,
                    focusedLabelColor = Grey,
                    unfocusedLabelColor = Grey,
                    cursorColor = custom,
                    textColor = custom,
    
                    ),
                onValueChange = { phoneNumberState.value = it },
                label = { Text(text = "Phone Number") },
                keyboardActions = KeyboardActions(onNext = {
                    focusManager.moveFocus(FocusDirection.Down)
                }),
                placeholder = { Text(text = "Phone Number") },
                singleLine = true,
                
                modifier = Modifier.fillMaxWidth(0.8f)
    
            )
    
             Button(
                    modifier = Modifier
                        .width(205.dp)
                        .height(35.dp),
                    onClick = {
                        focus.clearFocus(force = true)
                        model.onSignUp(
                            phoneNumberState.value,
                     
                        )
                        navController.navigate("otp")
    
                    },
                    colors = ButtonDefaults.buttonColors(
                        backgroundColor = custom
                    ),
                    shape = RoundedCornerShape(30)
                ) {
                    Text(
                        text = "Next",
                        style = TextStyle(
                            fontSize = 11.sp,
                            color = white,
    
                 ))
              }}

電話驗證屏幕:

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PhoneVerifyScreen(
    navController: NavController,
    modelAuthentication: AuthenticationViewModel,
    onClick: (mobileNum: String, otp: String) -> Unit
) {

    val focusManager = LocalFocusManager.current
    val phoneNumberOTP = remember { mutableStateOf("") }

    val context = LocalContext.current
    LaunchedEffect(Unit) {
        println("found activity? ${context.findActivity()}")
        val activity = context.findActivity() ?: return@LaunchedEffect
        modelAuthentication.setActivity(activity)
    }


    Column(
        Modifier.fillMaxSize()
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() } 
            ) {keyboardController?.hide()}
        ,
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {


        OutlinedTextField(
            value = phoneNumberOTP.value,
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = white,
                focusedIndicatorColor = Grey,
                unfocusedIndicatorColor = Grey,
                focusedLabelColor = Grey,
                unfocusedLabelColor = Grey,
                cursorColor = custom,
                textColor = custom,

                ),
            onValueChange = { phoneNumberOTP.value = it },
            label = { Text(text = "Verify code") },
            placeholder = { Text(text = "Verify code") },
            singleLine = true,
            modifier = Modifier.fillMaxWidth(0.8f),

        )


        CompositionLocalProvider(LocalRippleTheme provides NoRippleTheme) {
            Button(
                modifier = Modifier
                    .width(285.dp)
                    .height(55.dp),
                onClick = {

                    modelAuthentication.otpVerification(phoneNumberOTP.value)

                    navController.navigate("profileScreen")


                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = custom2
                ),
                shape = RoundedCornerShape(60),
           
            ) {
                Text(
                    text = "Next",
                    style = TextStyle(
                        fontSize = 18.sp,
                        color = white,


             ))
            }}}}

在您的MainActivity中創建一個viewModel ,這個 viewModel 將是共享的 viewModel,您可以將它傳遞給其他屏幕,或者只是將設置電話號碼的函數傳遞給該 sharedViewModel

class MainActivity : ComponentActivity() {
    private val sharedViewModel by viewModels<SharedViewModel>
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            App(sharedViewModel = sharedViewModel)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM