TextView背景颜色没有在android(kotlin)中更改单选按钮选择



我有一组单选按钮来切换应用程序上文本视图的背景颜色。这是按钮和文本视图的XML

<TextView
android:id="@+id/calcScreen"
android:layout_width="wrap_content"
android:layout_height="500dp"
android:fontFamily="monospace"
android:text="0"
android:textSize="48sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RadioGroup
android:id="@+id/bgColorChangeGRP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingHorizontal="14dp">
<RadioButton
android:id="@+id/_FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="Red background"
android:textSize="12sp" />
<RadioButton
android:id="@+id/_00FF00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="Green background"
android:textSize="12sp" />
<RadioButton
android:id="@+id/_0000FF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="Blue background"
android:textSize="12sp" />
</RadioGroup>
</LinearLayout>

正如你所看到的,我添加了一个名为onRadioButtonClicked的onClick方法,这是该函数的代码:

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onRadioButtonClicked(v: View){
val textView = findViewById<TextView>(R.id.calcScreen)
if (v is RadioButton) {
val checked = v.isChecked
when(v.getId()){
R.id._0000FF ->
if (checked) {
textView.setBackgroundColor(0xFF0000)
}
R.id._00FF00 ->
if (checked) {
textView.setBackgroundColor(0x00FF00)
}
R.id._0000FF ->
if (checked) {
textView.setBackgroundColor(0x0000FF)
}
}
}
}
}

每当我点击一个按钮,什么都不会发生。我尝试在测试中添加一个print语句,但在文本控制台中没有看到任何输出。我遵循了android教程,但似乎没有得到想要的输出。我认为这与onRadioButtonClicked函数如何获得id有关,但我不能100%确定。任何提示都将不胜感激。

if (checked) {
textView.setBackgroundColor(Color.parseColor("#FFFFFF"))
}

尝试将其用作

澄清为什么您的原始解决方案不起作用。因为你的按钮是透明的。第一个字节是alpha。

因此,您的颜色应该具有值,如:0xFFFF0000,以使您的颜色可见。开始时的FF是关键。

所以你的代码看起来像这样:

fun onRadioButtonClicked(v: View){
val textView = findViewById<TextView>(R.id.calcScreen)
if (v is RadioButton) {
val checked = v.isChecked
when(v.getId()){
R.id._FF0000 ->
if (checked) {
textView.setBackgroundColor(0xFFFF0000.toInt())
}
R.id._00FF00 ->
if (checked) {
textView.setBackgroundColor(0xFF00FF00.toInt())
}
R.id._0000FF ->
if (checked) {
textView.setBackgroundColor(0xFF0000FF.toInt())
}
}
}
}

最新更新