0
点赞
收藏
分享

微信扫一扫

Android(十九):RadioButton 单选 Checkbox 复选框


展示

Android(十九):RadioButton 单选 Checkbox 复选框_xml

源码

<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/rb01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="男"
android:checked="true" />

<RadioButton
android:id="@+id/rb02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="女" />

</RadioGroup>

<CheckBox
android:id="@+id/cb01"
android:layout_below="@id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="苹果"/>
<CheckBox
android:id="@+id/cb02"
android:layout_below="@id/cb01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="橘子"/>
<CheckBox
android:id="@+id/cb03"
android:layout_below="@id/cb02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="栗子"/>

using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Widget;

namespace android_by_csharp
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);

// 单选
var rg = (RadioGroup)FindViewById(Resource.Id.rg);
if (rg != null)
rg.CheckedChange += (sender, args) =>
{
var rb = (RadioButton)FindViewById(args.CheckedId);
Toast.MakeText(this, rb?.Text, ToastLength.Long)?.Show();
};

// 多选
var choose = new List<string>();
var cb01 = (CheckBox)FindViewById(Resource.Id.cb01);
var cb02 = (CheckBox)FindViewById(Resource.Id.cb02);
var cb03 = (CheckBox)FindViewById(Resource.Id.cb03);
if (cb01 != null)
cb01.CheckedChange += (sender, args) =>
{
if (args.IsChecked)
choose.AddRange(new[] { cb01.Text });
else
choose.RemoveAll(value => value == cb01.Text);
Toast.MakeText(this, string.Join(",", choose.ToArray()), ToastLength.Long)?.Show();
};
if (cb02 != null)
cb02.CheckedChange += (sender, args) =>
{
if (args.IsChecked)
choose.AddRange(new[] { cb02.Text });
else
choose.RemoveAll(value => value == cb02.Text);
Toast.MakeText(this, string.Join(",", choose.ToArray()), ToastLength.Long)?.Show();
};
if (cb03 != null)
cb03.CheckedChange += (sender, args) =>
{
if (args.IsChecked)
choose.AddRange(new[] { cb03.Text });
else
choose.RemoveAll(value => value == cb03.Text);
Toast.MakeText(this, string.Join(",", choose.ToArray()), ToastLength.Long)?.Show();
};
}
}
}


举报

相关推荐

0 条评论