Android Studio Java 选中复选框后的消息

AndroidStudio Java Message after checking a box

我试图在选中一个框时显示一条消息。问题是消息未显示。如果我在默认选中该框的情况下启动应用程序,该消息将只显示在开头,如果我尝试取消选中并再次选中,它不会再次出现。这是代码:

public class MainActivity extends AppCompatActivity {

    CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
        if (checkBox.isChecked())
            Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();
    }

您需要在复选框上设置侦听器。

checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){})

您需要为您的复选框实现一个侦听器以处理其点击。删除此行

 if (checkBox.isChecked())
        Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();

并使用此代码:

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                Toast.makeText(MainActivity.this, "Box was checked", Toast.LENGTH_SHORT).show();

            else
                Toast.makeText(MainActivity.this, "Box was unchecked", Toast.LENGTH_SHORT).show();

        }
    });