編輯:Android 開發實例
Spinner 是 Android 中常用的下拉選擇控制項。當預設樣式無法滿足需求時,我們可以透過自定義 ArrayAdapter,讓下拉列表呈現更豐富的內容——例如同時顯示文字與圖標。本文就來看看具體怎麼做。

這個佈局定義了每個下拉選項的外觀,左側是文字,右側是圖標:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/car_brand_name"
android:layout_gravity="left"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/car_brand_flag"
android:layout_gravity="right"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
關鍵在於重寫 getDropDownView 方法,為每個下拉項載入自定義佈局並填充資料:
ArrayAdapter carBrandAdapter = new ArrayAdapter<String>(
AddCarActivity.this,
android.R.layout.simple_spinner_dropdown_item,
carBrandNameList // 所有要顯示的 brandName 陣列
) {
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(AddCarActivity.this, R.layout.car_brand_spinner, null);
if (convertView != null) {
TextView carBrandNameView = (TextView) convertView.findViewById(R.id.car_brand_name);
ImageView carBrandFlagView = (ImageView) convertView.findViewById(R.id.car_brand_flag);
try {
JSONObject json = new JSONObject(carBrandList.get(position).get("carBrand").toString());
carBrandNameView.setText(json.getString("carBrandName")); // 設定品牌名稱
} catch (Exception e) {}
Bitmap bitmap = Common.String2Bitmap(carBrandList.get(position).get("carBrandFlagContent").toString());
if (bitmap != null)
carBrandFlagView.setImageBitmap(bitmap); // 顯示圖標
}
return convertView;
}
};
// 為 Spinner 設定適配器
Spinner carBrandSpinner = (Spinner) findViewById(R.id.carBrandSpinner);
carBrandSpinner.setAdapter(carBrandAdapter);
carBrandSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// 處理選項被選中的事件
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
透過重寫 getDropDownView,我們就能完全掌控下拉列表每一項的呈現方式,無論是加上圖標、自訂樣式還是排版,都能輕鬆實現。這正是自定義 Spinner 適配器的魅力所在。
Android 四大組件實戰:來電攔截與通話錄音
一、需求描述本實例借助 BroadcastReceiver 與 Service 兩大組件,實現兩個實用功能:1. 當手機有來電時,自動啟動監聽服務,對通話進行錄音。2.
Android 使用 ProgressBar 顯示載入中狀態
為什麼需要載入提示?在行動應用中,使用者常常需要等待資料載入。若畫面沒有任何回饋,使用者可能會以為應用沒有反應。此時,不確定型 ProgressBar 是很常見的解法。基
Android Dialog 去除白色邊框的實作思路與程式碼
用系統預設的 Dialog 樣式時,四周總會帶一圈白框,很多時候並不是我們想要的。要拿掉它,正解不是去改圖片,而是覆寫樣式。 第一步:自訂 style 在 values
Android 中的 SAX 解析:事件驅動的 XML 讀寫實作
Android 上處理 XML 有兩條路:DOM 與 SAX。DOM 會把整份文件讀進記憶體再操作,方便隨意跳轉查詢,但記憶體開銷大;SAX 則是事件驅動,解析器一邊讀一