'color change kotlin and activity refresh

I am new to programming and kotlin. I am using a calculation where I have two edittext numbers a, b and a button called Calculate. Also, I have added 3 Textview
1- moreThan
2- equalTo
3- lessThan

I went to the main activity using if statement and I programmed the color change of the textView depending on the calculation.

to illustrate

if ((a+b)<3){
lessThan.setTextColor(Color.parseColor("#FFFF00")) <<< yellow
}
else if ((a+b)=3){
equalTo.setTextColor(Color.parseColor("#333333"))  <<<gray
}
else if ((a+b)>3){
moreThan.setTextColor(Color.parseColor("#ff0000")) <<< red
}

Everything is good, but the problem is with the colors, they don't return to default upon clicking button for the second time. to illustrate:
a = 7
b = 10
I click calculate
a+b = 17 which is over than 3, moreThan TextView changes color to red


Now, I change values
a= 1
b= 1
I click calculate
a+b = 2 witch is less than 3, lessThan TextView changes color to yellow [[Good]] // !!!! but moreThan is still red from old calculation.


I hope I did explain the issue I am facing.



Solution 1:[1]

moreThan is still red because you haven't changed it back. When you find a matching condition, you don't just need to set the colour of the matching TextView, you need to reset the others too!

You could try and keep track of the last TextView that was highlighted, so you can put it back to the default colour, but it's easier to think in terms of an overall state:

3 states:

More than
 - moreThan is RED
 - lessThan is DEFAULT
 - equalTo is DEFAULT

Equal to
 - moreThan is DEFAULT
 - lessThan is DEFAULT
 - equalTo is GRAY

Less than
 - moreThan is DEFAULT
 - lessThan is YELLOW
 - equalTo is DEFAULT

so whichever condition matches, this is how you need to set things up. By explicitly setting each TextView's colour to what it's meant to be, you know you're displaying the correct state, and it's just easier to keep track of things.

You can do that in your condition check

if ((a+b)<3){
    lessThan.setTextColor(Color.parseColor("#FFFF00")) <<< yellow
    equalTo.setTextColor(DEFAULT) // <- you can define this somewhere, set it to a colour
    moreThan.setTextColor(DEFAULT)
}
// etc

Get the idea? By setting everything together you know it's all correct, and you don't have anything left over from what was being displayed before. This is important if you start using things like RecyclerViews, where the item displays get reused, and you have to set everything to make sure it's accurate (and you don't have, for example, a checkbox that stays checked because it was checked for the last item)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cactustictacs