分類:C#、Android、VS2015;
創建日期:2016-02-07
1、CheckBox
復選
【Checked】屬性:是否選中。
2、RadioButton
單選
【Checked】屬性:是否選中。
【RadioGroup】屬性:RadioButton的分組容器。注意必須將RadioButton包含在RadioGroup內。
1、運行截圖
2、添加demo04_CheckBoxRadioButton.axml文件
在layout文件夾下添加該文件。
從【工具箱】中向設計界面拖放2個【CheckBox】控件,1個【RadioGroup】控件,然後直接在【源】中將其修改為下面的內容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:text="紅色"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/checkBoxRed" />
<CheckBox
android:text="綠色"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkBoxGreen" />
<RadioGroup
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/radioGroupGander">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男"
android:id="@+id/radioButtonMale" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女"
android:id="@+id/radioButtonFamale" />
</RadioGroup>
<Button
android:id="@+id/btnOK"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="確定" />
</LinearLayout>
3、添加Demo04CheckBoxRadioButton.cs文件
在SrcActivity文件夾下添加該文件。
using System;
using Android.App;
using Android.OS;
using Android.Widget;
namespace ch05demos.SrcActivity
{
[Activity(Label = "CheckBoxRadioButtonDemo")]
public class Demo04CheckBoxRadioButton : Activity
{
CheckBox red, green;
RadioButton nan, nv;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.demo04_CheckBoxRadioButton);
red = FindViewById<CheckBox>(Resource.Id.checkBoxRed);
green = FindViewById<CheckBox>(Resource.Id.checkBoxGreen);
nan = FindViewById<RadioButton>(Resource.Id.radioButtonMale);
nv = FindViewById<RadioButton>(Resource.Id.radioButtonFamale);
var button = FindViewById<Button>(Resource.Id.btnOK);
button.Click += Button_Click;
}
private void Button_Click(object sender, EventArgs e)
{
string s1 = "性別:" + (nan.Checked ? "男" : "女");
string s2 = "喜歡的顏色:";
if (red.Checked) s2 += red.Text;
if (green.Checked) s2 += " " + green.Text;
Toast.MakeText(this,
string.Format("{0}\n{1}", s1, s2),
ToastLength.Long).Show();
}
}
}
運行觀察該例子的效果。
提示:通過【Checked】屬性或Toggle()方法都可以改變RadioButton的狀態。