Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下拉選單 Spinner 的實作範例

編輯:關於 Android 程式設計

Spinner 的作用有點像 HTML 裡的下拉框 <select></select>:使用者點開後從清單中挑選一項。本文分享具體的實現代碼,供大家參考。

main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Main" >

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="300sp"
        android:layout_height="50sp"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

Main.java

package com.app.main;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class Main extends Activity {

    Spinner spinner = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        spinner = (Spinner) this.findViewById(R.id.spinner);

        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_spinner_item,
                new String[] { "第一項", "第二項", "第三項" });

        // 設置下拉樣式
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);
    }
}

效果如下:

這裡其實牽涉到兩個系統 XML:一個是填充資料時用的 simple_spinner_item.xml,另一個是控制下拉樣式的 simple_dropdown_item_1line.xml。理解這兩者的分工,有助於日後替換成自訂樣式。

simple_spinner_item.xml

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:textAlignment="inherit" />

simple_dropdown_item_1line.xml

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:textAppearance="?android:attr/textAppearanceLargePopupMenu"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:ellipsize="marquee" />

以上就是本文的全部內容,希望對大家學習 Android 軟體編程有所幫助,也歡迎多多支持本站。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved