【发布时间】:2019-03-10 07:15:33
【问题描述】:
我想学习如何使用监听器onCheckedChangeListener,但是每次我实现它时,应用程序都会关闭。我知道可以用onCLick 完成,但我需要知道如何使用它:
package com.example.tonij.colores;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
CheckBox rojo,verde,azul;
Button ponerColor, borrar;
TextView texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
rojo= (CheckBox) findViewById(R.id.botonRojo);
verde= (CheckBox) findViewById(R.id.botonVerde);
azul= (CheckBox) findViewById(R.id.botonAzul);
rojo.setOnCheckedChangeListener(
new CheckBox.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked==true){
texto.setText("enga");
}
}
}
);
ponerColor= (Button) findViewById(R.id.ponerColor);
borrar= (Button) findViewById(R.id.borrar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
【问题讨论】:
-
不确定你想要什么,但你还没有初始化你的
textToTextView,它肯定会崩溃。还将if(isChecked==true)更改为if(isChecked)。好难受 -
好的,谢谢,但我认为这不是问题,当我使用代码时它返回给我一个空点异常 --> 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.widget.CheckBox.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)'