我想使用按钮来处理复选框。 当我按下“检查”按钮时,我想写下它是假还是真,以及如何让用户仅从选项中选中1个复选框?
package com.example.android.qa;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Question1(View v) {
CheckBox Html = (CheckBox) findViewById(R.id.Html);
boolean hasHtml = Html.isChecked();
CheckBox Css = (CheckBox) findViewById(R.id.Css);
boolean hasCss = Css.isChecked();
CheckBox JavaScript = (CheckBox) findViewById(R.id.Java_Script);
boolean hasJavaScript = JavaScript.isChecked();
String Answer1 = Question1Active("True", "False","False");
}
public String Question1Active(String Html, String Css, String JavaScript){
String Answer1 = "\n" + getString(R.string.True) + Html;
Answer1 = "\n" + getString(R.string.False) + Css;
Answer1 = "\n" + getString(R.string.False) + JavaScript;
return Answer1;
}
}
答案 0 :(得分:0)
使用RadiGroup
如果我们选中属于某个广播组的一个单选按钮,它将自动取消选中同一组中以前选中的任何单选按钮。
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_below="@+id/imageView"
android:layout_marginTop="58dp"
android:weightSum="1"
android:id="@+id/radioGroup"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2"
android:layout_alignRight="@+id/textView3"
android:layout_alignEnd="@+id/textView3">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="55dp"
android:text="Male"
android:id="@+id/radioButton"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:layout_weight="0.13" />
</RadioGroup>
您的Java代码:
radioGroup = (RadioGroup) findViewById(R.id.myRadioGroup);
firstRadioButton= (RadioButton) findViewById(R.id.firstRadioButton);
secondRadioButton= (RadioButton) findViewById(R.id.secondRadioButton);
//查找选择了哪个单选按钮
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override public void onCheckedChanged(RadioGroup group, int
checkedId) {
// find which radio button is selected
if(checkedId == R.id.firstRadioButton) {
Toast.makeText(getApplicationContext(), "choice: firstRadioButton",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.secondRadioButton) {
Toast.makeText(getApplicationContext(), "choice: SeconRadioButton",
Toast.LENGTH_SHORT).show();
}
});