我想将“ colorSRMx”放在变量上,然后从类似的地方调用它。如何编写更有效的代码。
colorint = getColor(resources, R.color."VARIABLE", null)
sbarSRMColor.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
txtsrm = progress.toString()
when (txtsrm) {
"1" -> colorint = getColor(resources,R.color.colorSRM1,null)
"2" -> colorint = getColor(resources,R.color.colorSRM2,null)
"3" -> colorint = getColor(resources,R.color.colorSRM3,null)
"4" -> colorint = getColor(resources,R.color.colorSRM4,null)
// and so on...
}
value.setBackgroundColor(colorint)
}
}
答案 0 :(得分:0)
fun Activity.parseColorSafe(colorString: String): Int{
return try {
Color.parseColor(colorString)
} catch (exception: Exception) {
resources.getColor(R.color.transparent)
}
}
在您的活动中,使用类似parseColorSafe(colorSRM1)