im a newbie currently working on a health app school project.
i have found a problem when i was trying to change a TextView background with a drawable refrence. it like the color of the text view doesnt follow my line of program, but in some condition it runs perfectly.
private fun updateIndikatorAu(){
//Colors
val colorHigh = "#e85218"
val colorNormal = "#6b91ca"
val colorLow = "#eeaf17"
val colorNull = "#7F808B"
//Fields
indiAu = findViewById(R.id.textindi_au)
kadarAu = findViewById(R.id.textkadarprof_au)
satuanAu = findViewById(R.id.textsatuanprof_au)
judulAu = findViewById(R.id.textprof_au)
//Nilai
val nilaiNullAU = 0
val nilaiProfAU = kadarAu.text.toString()
val nilai1AU = 7.0
//converter Double
val auNol = nilaiNullAU.toDouble()
val auNormal1 = nilai1AU.toDouble()
val auProf = nilaiProfAU.toDouble()
//Nilai Tinggi
if (auProf > auNormal1){
indiAu.setBackgroundResource(R.drawable.highbuttoncolor)
satuanAu.setBackgroundColor(R.drawable.highbuttoncolor)
kadarAu.setTextColor(android.graphics.Color.parseColor(colorHigh))
judulAu.setTextColor(android.graphics.Color.parseColor(colorHigh))
}
//Nilai Normal
else if (auProf > auNol && auProf < auNormal1){
indiAu.setBackgroundColor(R.drawable.normalbuttoncolor)
satuanAu.setBackgroundColor(R.drawable.normalbuttoncolor)
kadarAu.setTextColor(android.graphics.Color.parseColor(colorNormal))
judulAu.setTextColor(android.graphics.Color.parseColor(colorNormal))
}
//Nilai 0
else if (auProf == auNol){
indiAu.setBackgroundColor(R.drawable.nullbuttoncolor)
satuanAu.setBackgroundColor(R.drawable.nullbuttoncolor)
kadarAu.setTextColor(android.graphics.Color.parseColor(colorNull))
judulAu.setTextColor(android.graphics.Color.parseColor(colorNull))
}
}
i have use the same method to change the background color before setBackgroundColor(android.graphics.Color.parseColor(colorHigh))
like the text color change code.
it works fine but i need to maintain the rounded corner. so i use R.drawable.highbuttoncolor
instead android.graphics.color.parseColor(colorHigh)
. but the button color doesnt change perfectly.
please help me fix this problem, or explain me the condition why this problem can happen. i’ll really grateful.
2
Answers
setBackgroundColor
does change the color of theView
but also overrides the shape of theView
to the default one. You should not be usingsetBackgroundColor
if You also want to have a specific shape of theView
.You should use only
setBackgroundResource
with adrawable
resource that defines both the shape and the color "in one go", something like this:and then:
Also remember that colors should be defined in the
colors.xml
file.Hey if you are using a
drawable
for setting the background you should use :But for just the color it would be:
From codewise i guess the first condition is working because you are using the correct one:
but second and third condition you always only use:
So use there also
setBackgroundResource()