Android控件入门-单选多选控件

单选:

xml:



<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    

    

    

    

java:

private RadioButton ra;
ra = findViewById(R.id.java);
Button btnSubmit = findViewById(R.id.submit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (ra.isChecked()) {
            Toast.makeText(MainActivity.this, "选择正确", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "选择错误", Toast.LENGTH_SHORT).show();
        }
    }
});

多选:

xml:











java:

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener
private CheckBox cb1, cb2, cb3, cb4;
private TextView show;
show = findViewById(R.id.show);
cb1 = findViewById(R.id.php1);
cb2 = findViewById(R.id.java1);
cb3 = findViewById(R.id.python1);
cb4 = findViewById(R.id.javascript);

cb1.setOnCheckedChangeListener(this);
cb2.setOnCheckedChangeListener(this);
cb3.setOnCheckedChangeListener(this);
cb4.setOnCheckedChangeListener(this);
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    String str = "你会";

    if (cb1.isChecked()){
        str += cb1.getText() + ",";
    }
    if (cb2.isChecked()){
        str += cb2.getText() + ",";
    }
    if (cb3.isChecked()){
        str += cb3.getText() + ",";
    }
    if (cb4.isChecked()){
        str += cb4.getText() ;
    }

    show.setText(str);
}

你可能感兴趣的:(Android开发)