編輯:關於 Android 程式設計
單選按鈕(RadioButton)與核選框(CheckBox)都是提供使用者快速選擇的良好體驗:在不需要使用者親手輸入的場合,這類控制項能讓操作更為便捷。兩者的差別在於——RadioButton 在一組選項中只能選擇其中一個,而 CheckBox 則可以勾選多個。以下以 RadioButton 為例示範。
先在版面配置檔中定義一組單選按鈕,分為三個選項:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- 定義一組 RadioButton,分為三個選項 -->
<RadioButton
android:id="@+id/first_radiobutton"
android:checked="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onAction"
android:text="男" />
<RadioButton
android:id="@+id/second_radiobutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onAction"
android:text="女" />
<RadioButton
android:id="@+id/third_radiobutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onAction"
android:text="其他" />
</LinearLayout>
其中 android:checked="true" 用來設定預設被勾選的選項;android:onClick="onAction" 則是設定點擊事件的監聽方法,實際的行為在 Java 程式碼中實作。若要將多個按鈕歸為同一組,可使用 RadioGroup 來定義。
package xbb.bzq.android.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class RadioButtonAndCheckBoxTestActivity extends Activity {
// 定義三個 RadioButton 變數
private RadioButton mButton1, mButton2, mButton3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 實例化三個單選按鈕控制項
mButton1 = (RadioButton) findViewById(R.id.first_radiobutton);
mButton2 = (RadioButton) findViewById(R.id.second_radiobutton);
mButton3 = (RadioButton) findViewById(R.id.third_radiobutton);
}
/**
* 這是實作的監聽方法,主要用來切換選項的勾選狀態
* @param v
*/
public void onAction(View v) {
// 透過取得 id 來判斷使用者的選擇,再改變控制項的勾選狀態
switch (v.getId()) {
case R.id.first_radiobutton:
mButton2.setChecked(false);
mButton3.setChecked(false);
mButton1.setChecked(true);
break;
case R.id.second_radiobutton:
mButton1.setChecked(false);
mButton3.setChecked(false);
mButton2.setChecked(true);
break;
case R.id.third_radiobutton:
mButton2.setChecked(false);
mButton1.setChecked(false);
mButton3.setChecked(true);
break;
}
}
}
透過 onAction 方法判斷被點擊的選項,並將其餘選項設為未勾選、將目前選項設為勾選,即可實現單選的互斥效果。
Android Volley 實戰:從建置 jar 到 GET、POST、JSON 請求
Volley 是 Google 開發的網路庫,讓存取網路資料這件事變得簡單又快速,而且所有請求天生就是非同步的,不必再為非同步處理傷腦筋。它主要的優點有:具備請求佇列與優
Android 學習心得:回歸技術的本真
做 Android 開發也有一段時間了,卻很少寫博客。今天算是第一次真正意義上在平台上發表自己的一些看法,心裡既欣喜也有些壓力。欣喜的是能把自己的想法攤開來與大家交流;有
在 UbuntuKylin 16.04.1 上從零搭建 Android 開發環境
前段時間和同學聊天,聽說他們公司準備把開發環境從 Windows 遷到 Linux。我突然意識到自己還沒在 Linux 上搭過 Android 開發環境,於是趁著有空試了
Android 繪圖基礎(一):Paint 畫筆詳解
接觸過 Android 繪圖或自定義 View 的同學,對 Canvas、Paint 這兩個類應該都不陌生。今天我們重點來看看 Paint 的用法。 先看看官方定義: T