RadioGroup,Radio单选按钮,CheckBox的使用

xml文件中:

<RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="45dp" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="pepelu" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="cc" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="lulu" />
    </RadioGroup>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/radioGroup1"
        android:layout_below="@+id/radioGroup1"
        android:layout_marginLeft="83dp"
        android:layout_marginTop="147dp"
        android:text="TextView" />

activity中:

public class MainActivity extends Activity {
    TextView textView;
    HashMap<Integer, String> radio;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        textView = (TextView) findViewById(R.id.textView1);
        radio=new HashMap<Integer, String>();
        radio.put(R.id.radio0, "cc");
        radio.put(R.id.radio1, "pepelu");
        radio.put(R.id.radio2, "lulu");
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                textView.setText(radio.get(checkedId));
            }
        });
    }

}

使用HashMap保存数据是因为Radio的id不是连续的,并且是唯一的,非常符合HashMap的key规则。

使用OnCheckedChangListener监听RadioGroup中单个Radio的选中状态。

TextView输出对应结果。

CheckBox使用:

 public class MyActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         final CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox_id);
         if (checkBox.isChecked()) {
             checkBox.setChecked(false);
         }
     }
 }
原文地址:https://www.cnblogs.com/mada0/p/4821610.html