As I was working on this code yesterday after I tried using SaveInstanceState for saving my textview output while changing my orientation from portrait to landscape mode but it didn't work. so i thought and realized that i could work it out using View Model state but. unlike SaveInstance State, I tried doing View Model but i find it little tough to do and fix the errors, here is the code for main activity and ViewModel
Main Activity kotlin
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var count = 10
val textCount = findViewById<View>(R.id.textView) as TextView
val buttonred = findViewById<View>(R.id.injury) as Button
val buttoning = findViewById<View>(R.id.revive) as Button
var viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
buttonred.setOnClickListener {
if (count >= 0) {
count--
textCount.text = count.toString()
}
}
buttoning.setOnClickListener {
if (count <= 10) {
count += 2
textCount.text = count.toString()
}
}
}
}
Viewmodel kotlin code (note: i just started working on it, but i have no idea how to work it out)
class MainActivityViewModel: ViewModel() {
var count = 10
fun medivial()
{
count--
}
}
here is the xml file
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="60dp"
android:layout_height="78dp"
android:layout_marginStart="145dp"
android:layout_marginTop="68dp"
android:layout_marginEnd="145dp"
android:textSize="50dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/injury"
android:layout_width="106dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="150dp"
android:text="injury"
/>
<Button
android:id="@+id/revive"
android:layout_width="197dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="109dp"
android:text="revive" />
</LinearLayout>
need help on this
You have to add LiveData to the ViewModel class and observe it. Your activity class cannot have any data like
count. ViewModel has to carry all actions and just give data to View (MainActivity)To Your Gradle (module.app) file add:
MainActivityViewModel class:
MainActivity class: