LiveData in Kotlin

viewBinding {
enabled = true
}
<?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/number_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:textSize="75sp"
android:textAlignment="center" />

<Button
android:id="@+id/add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/number_text_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginTop="20dp"
android:text="Add" />
</androidx.constraintlayout.widget.ConstraintLayout>
class MainViewModel : ViewModel() {

private val _numberOfTaps = MutableLiveData<Int>(0)
val numberOfTaps = _numberOfTaps

fun addNumber() {
_numberOfTaps.value = _numberOfTaps.value?.plus(1)
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)

mainViewModel.numberOfTaps.observe(this) { numberOfTaps ->
binding.numberTextView.text = numberOfTaps.toString()
}

binding.addButton.setOnClickListener {
mainViewModel.addNumber()
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alexander Portillo

Alexander Portillo

20 Years Old | Pursing Android Development