2016年2月16日 星期二

單選選單

Layout:RadioGroup內預設包含3個RadioButton

<RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/radioGroup1">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true" // 預設點選此項,如果沒有的話,就沒有點選
            android:text="Visual Studio"
            android:id="@+id/radioVS" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Xamarin Studio"
            android:id="@+id/radioXS" />
        <TextView  //用來顯示誰被點選
            android:text="點選上方選項"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtRadio" />
        <Button
            android:text="取得值"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btnRadio" />
    </RadioGroup>



Activity:重點在於判斷誰被點選,並將值取出
            //...RadioGroup / Button
            var txtRadio = this.FindViewById<TextView>(Resource.Id.txtRadio);
            var radioGroup = this.FindViewById<RadioGroup>(Resource.Id.radioGroup1);
            //判斷誰被點選了
            radioGroup.CheckedChange += (sender, e) =>
            {
                int id = e.CheckedId; //被點選者資訊傳給id
                var select = this.FindViewById<RadioButton>(id);//讀取被點選RadioButton資訊
                txtRadio.Text = string.Format("你點選了{0}", select.Text);
                //讀取select之Text屬性內容,覆寫至txtRadio之Text屬性內容

            };
            //另一種判斷誰被點選方式by btn
            var btnRadio = this.FindViewById<Button>(Resource.Id.btnRadio);
            btnRadio.Click += (sender, e) =>
            {
                var select = this.FindViewById<RadioButton>
                    (radioGroup.CheckedRadioButtonId); //重點指令
                txtRadio.Text = string.Format("按鈕取得了{0}", select.Text);
            };
            //...RadioGroup / Button




沒有留言:

張貼留言