2016年2月26日 星期五

checkBox

Layout :

<TextView
        android:text="未選擇"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt" />
    <CheckBox
        android:text="香蕉"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cbBanana" />
    <CheckBox
        android:text="西瓜"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cbWatermelon" />
    <CheckBox
        android:text="鳳梨"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cbAnanas" />
    <CheckBox
        android:text="草莓"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/cbStrawberry" />

Activity:

            FindViewById<CheckBox>(Resource.Id.cbBanana)
                .CheckedChange += CheckedChange;
            FindViewById<CheckBox>(Resource.Id.cbWatermelon)
                .CheckedChange += CheckedChange;
            FindViewById<CheckBox>(Resource.Id.cbAnanas)
                .CheckedChange += CheckedChange;
            FindViewById<CheckBox>(Resource.Id.cbStrawberry)
                .CheckedChange += CheckedChange; //checkedchange副程式在底下

//..Smart 寫法 (將上面四個FindViewById改成下述程式碼 )
//不用每個checkBox都定義,以迴圈方式自動定義,則可自由新增checkBox而不受影響
            var cbLayout = FindViewById<LinearLayout>(Resource.Id.cbLayout);//定義LinearLayout裡面的所有cbLayout
            int cbCount = cbLayout.ChildCount;
            for (int i = 0; i < cbCount; i++)
            {
                var cbItem = cbLayout.GetChildAt(i);
                if (cbItem is CheckBox)
                {
                    ((CheckBox)cbItem)
                        .CheckedChange += CheckedChange;
                }
            }

//..Smart 寫法

private List<string> _cacheSelect = new List<string>(); //如果checkbox被選取,值就會寫到List中


void CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
        {
            var txt =
                FindViewById<TextView>(Resource.Id.txt);
            var cb = ((CheckBox)sender);
            if (e.IsChecked)
                _cacheSelect.Add(cb.Text);  //被選到的cb,其text會被加到_cacheSelect
            else
                _cacheSelect.Remove(cb.Text);
            txt.Text = GenSelectString();
        }

private string GenSelectString() //將所有被選擇的CB值集合至此處一次顯示
        {
            StringBuilder select = new StringBuilder();
            foreach (var s in _cacheSelect)
                select.AppendFormat(",{0}", s);
            if (string.IsNullOrEmpty(select.ToString()))
                return "未選擇";
            else
                return "你選擇了" + select.ToString().Substring(1);
        }




沒有留言:

張貼留言