Ejemplo de ViewModel en Kotlin
Ejemplo de uso de ViewModel
ViewModel Explained
Crear un nuevo proyecto en Kotlin llamado Vista Modelo
ViewBinding en build.gradle
buildFeatures { viewBinding = true }
dependencias
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="128dp" android:layout_height="57dp" android:text="0" android:textAlignment="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textSize="40sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.207" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add +1" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textSize="40sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.129" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivityViewModel.kt
class MainActivityViewModel : ViewModel() { var number = 0 fun addNumber() { number++ } }
MainActivity.kt
class MainActivity : AppCompatActivity(), View.OnClickListener { lateinit var viewmodel: MainActivityViewModel lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_main) binding = ActivityMainBinding.inflate(layoutInflater) val view: View = binding.root setContentView(view) binding.button.setOnClickListener(this) viewmodel = ViewModelProvider(this).get(MainActivityViewModel::class.java) binding.textView.text = viewmodel.number.toString() } override fun onClick(view: View) { if (view === binding.button) { viewmodel.addNumber() binding.textView.text = viewmodel.number.toString() } } }
Codelab:
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.