Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
Cómo usar Viewmodel con Jetpack componer

Estoy tratando de usar ViewModel con Jetpack Compose,

Haciendo un incremento de número.

Pero no está funcionando. Tal vez no estoy usando el modelo de vista de la manera correcta.

Aquí está mi código de actividad principal

 class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Greeting() } } } @Composable fun Greeting( helloViewModel: ViewModel = viewModel() ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxSize() ) { Text( text = helloViewModel.number.toString(), fontSize = 60.sp, fontWeight = FontWeight.Bold ) Button(onClick = { helloViewModel.addNumber() }) { Text(text = "Increment Number ${helloViewModel.number}") } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { JetpackcomposepracticeTheme { Greeting() } }

Y aquí está mi clase Viewmodel.

Funciona bien con xml.

¿Cómo creo el modelo de objeto de vista?

 class ViewModel: ViewModel() { var number : Int = 0 fun addNumber(){ number++ } }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Compose puede recomponerse cuando cambia algún contenedor de valor de estado mutable. Puede crearlo manualmente con mutableStateOf() , mutableStateListOf() , etc., o envolviendo Flow / LiveData .

 class ViewModel: ViewModel() { var number : Int by mutableStateOf(0) private set fun addNumber(){ number++ } }

Le sugiero que comience con el estado en la documentación de redacción, incluido este video de YouTube que explica los principios básicos.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!