首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Spinner 動態載入 strings.xml 字串陣列資源

     編輯:程式設計綜合問答

需求場景

在 strings.xml 定義字串陣列資源,動態載入並設定給 Spinner 的 ArrayAdapter。

資源定義 (res/values/strings.xml)

<resources>
    <string-array name="country_array">
        <item>台灣</item>
        <item>美國</item>
        <item>日本</item>
        <item>韓國</item>
        <item>新加坡</item>
    </string-array>
    
    <string-array name="city_array">
        <item>台北</item>
        <item>紐約</item>
        <item>東京</item>
        <item>首爾</item>
        <item>新加坡</item>
    </string-array>
</resources>

正確載入方式

// 1. 從資源取得字串陣列
String[] countries = getResources().getStringArray(R.array.country_array);

// 2. 建立 ArrayAdapter 並指定下拉樣式
ArrayAdapter adapter = new ArrayAdapter<>(
    this,                                    // Context
    android.R.layout.simple_spinner_item,    // 預設項目佈局
    countries                                // 資料來源
);

// 3. 設定下拉選單樣式(必須)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// 4. 套用至 Spinner
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(adapter);

動態切換資料來源範例

public class DynamicSpinnerActivity extends AppCompatActivity {
    private Spinner spinner;
    private RadioGroup radioGroup;
    private ArrayAdapter adapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_spinner);
        
        spinner = findViewById(R.id.spinner);
        radioGroup = findViewById(R.id.radio_group);
        
        // 初始載入預設資料
        loadSpinnerData(R.array.country_array);
        
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.radio_countries) {
                loadSpinnerData(R.array.country_array);
            } else if (checkedId == R.id.radio_cities) {
                loadSpinnerData(R.array.city_array);
            }
        });
    }
    
    private void loadSpinnerData(int arrayResId) {
        String[] data = getResources().getStringArray(arrayResId);
        
        if (adapter == null) {
            adapter = new ArrayAdapter<>(
                this, 
                android.R.layout.simple_spinner_item, 
                data
            );
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
        } else {
            // 更新現有 Adapter 資料
            adapter.clear();
            adapter.addAll(data);
            adapter.notifyDataSetChanged();
        }
    }
}

佈局檔案 (activity_dynamic_spinner.xml)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">
    
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        <RadioButton
            android:id="@+id/radio_countries"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="國家"
            android:checked="true" />
            
        <RadioButton
            android:id="@+id/radio_cities"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="城市" />
    </RadioGroup>
    
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp" />
        
</LinearLayout>

進階:自訂項目佈局

建立 res/layout/spinner_item.xml:

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="16sp"
    android:textColor="#333"
    android:ellipsize="end"
    android:maxLines="1" />

使用自訂佈局:

ArrayAdapter adapter = new ArrayAdapter<>(
    this, 
    R.layout.spinner_item,  // 自訂項目佈局
    data
);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item); // 下拉樣式也可自訂

常見錯誤與解決

錯誤原因解決
Spinner 顯示空白未呼叫 setDropDownViewResource()必須設定下拉樣式資源
資料不更新直接新建 Adapter 但未 setAdapter()更新現有 Adapter 用 clear()/addAll()/notifyDataSetChanged()
R.array 找不到資源檔案命名或路徑錯誤確認在 res/values/strings.xml 定義 <string-array name="xxx">
中文亂碼檔案編碼非 UTF-8Android Studio 預設 UTF-8,檢查檔案編碼設定

總結

使用 getResources().getStringArray(R.array.name) 取得字串陣列,建立 ArrayAdapter 時**必須呼叫 setDropDownViewResource()** 設定下拉樣式。動態切換資料時,優先更新現有 Adapter 而非重建,效能更好且避免閃爍。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved