Reputation: 55
I am running an app that has 2 buttons, one for increasing value and another for decreasing value. In this, I need to run the values between 10 and 0 but I couldn't do it(whenever I run the app, it goes below 0 and over 10).
class MainActivity : AppCompatActivity() {
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.vial) as Button
if (count >= 0) {
println(count)
buttonred.setOnClickListener {
count--
textCount.text = count.toString()
}
if (count <= 10)
{buttoning.setOnClickListener {
count += 3
textCount.text = count.toString()
}}
}
}
XML
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/vial"
android:layout_width="197dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="109dp"
android:text="vial" />
</LinearLayout>
I need help to clear this.
Upvotes: 1
Views: 70
Reputation: 386
Just remove "=" i.e
if (count > 0) { println(count) buttonred.setOnClickListener { count-- textCount.text = count.toString()
}
if (count < 10)
{buttoning.setOnClickListener {
count += 3
textCount.text = count.toString()
}}
Upvotes: 0
Reputation: 1408
I believe your logic is wrong.
The most primary thing to understand is the IF condition
count <= 10 && count >= 0
In Basic English this means: count can only be less than and equal to 10 AND greater than and equal to 0. This would make sure that both buttonRed
and buttonIng
will not surpass values 0 to 10 when they are clicked.
buttonRed.setOnClickListener {
if (count >= 0 && count <= 10) {
count++
textCount.text = count.toString()
}
}
buttonIng.setOnClickListener {
if (count <= 10 && count >= 0) {
count--
textCount.text = count.toString()
}
}
Upvotes: 0
Reputation: 71
how if you move if statement
inside the listener
buttonred.setOnClickListener {
if(count >= 0){
count--
textCount.text = count.toString()
}
}
buttoning.setOnClickListener {
if(count <= 10){
count += 3
textCount.text = count.toString()
}
}
Upvotes: 1