DynamicAdd.axml 內只有一個 LinearLayout
<?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"
android:id="@+id/Layout" />
DynamicActivity.csnamespace CheckBoxBase
{
[Activity(Label = "DynamicActivity", MainLauncher = true)]
public class DynamicActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.DynamicAdd);
// 動態產生 CheckBox
LinearLayout layout = FindViewById<LinearLayout>(Resource.Id.Layout);
for (int i = 0; i < 5; i++)
{
CheckBox cb = new CheckBox(this);
cb.Text = $"Dynamic{i}";
cb.CheckedChange += Cb_CheckedChange;
layout.AddView(cb);
}
}
private void Cb_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
LinearLayout layout = FindViewById<LinearLayout>(Resource.Id.Layout);
StringBuilder sb = new StringBuilder();
sb.AppendLine($"目前勾選: {((CheckBox)sender).Text},狀態為:{e.IsChecked}");
sb.AppendLine("---------------------------");
sb.AppendLine("顯示全部 CheckBox 狀態");
int ctls = layout.ChildCount;
for (int i = 0; i < ctls; i++)
{
View v = layout.GetChildAt(i);
if ((v is CheckBox) == false) continue;
CheckBox cb = v as CheckBox;
sb.AppendLine(cb.Text + "狀態為" + (cb.Checked == true ? "已勾選" : "未勾選"));
}
Toast.MakeText(this, sb.ToString(), ToastLength.Short).Show();
}
}
}
沒有 ofType() 可以使用就要多寫點 Code 來判斷是不是 CheckBox 控件
![[X.Andriod] 動態產生 CheckBox-1](https://c1.staticflickr.com/8/7324/27694740720_cc84573a3c.jpg)
![[X.Andriod] 動態產生 CheckBox-2](https://c4.staticflickr.com/8/7236/27896970491_91e2fc8559_b.jpg)
沒有留言:
張貼留言