Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
How to use Viewmodel with Jetpack compose

I am trying to use ViewModel with Jetpack Compose,

By doing a number increment.

But it's not working. Maybe I'm not using the view model in right way.

Heres my Main Activity code

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()
    }
}

And here is my Viewmodel class.

It works fine with xml.

How do i create the object of view model:

class ViewModel: ViewModel() {
    var number : Int = 0
    fun addNumber(){
        number++
    }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Compose can recompose when some with mutable state value container changes. You can create it manually with mutableStateOf(), mutableStateListOf(), etc, or by wrapping Flow/LiveData.

class ViewModel: ViewModel() {
    var number : Int by mutableStateOf(0)
        private set

    fun addNumber(){
        number++
    }
}

I suggest you start with state in compose documentation, including this youtube video which explains the basic principles.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda