Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

299
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda