Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Android 初學:OnItemSelectedListener 事件怎麼用

編輯:Android 技術基礎

下拉列表框 Spinner 是最常見的「多選一」控件,而它和程式之間的橋樑,就是 OnItemSelectedListener。本章用最簡單的單一 Spinner 例子,把這個事件的註冊與回呼流程走一遍。

一、準備界面

1. 新增 province.xml

在 res/values 下建立 province.xml,定義省份陣列。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="provarray">
        <item>河南省</item>
        <item>河北省</item>
        <item>山東省</item>
        <item>山西省</item>
    </string-array>
</resources>

2. 拖一個 Spinner 進版面

打開 res/layout/activity_main.xml,從 Form Widgets 拖出一個 Spinner,並用 android:entries 關聯剛剛寫好的陣列。

<RelativeLayout 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"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/province"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:entries="@array/provarray" />

</RelativeLayout>

3. 預覽

二、OnItemSelectedListener 事件

打開 src/com.genwoxue.onitemselected/MainActivity.java,寫入下列程式:

package com.genwoxue.onitemselected;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {

    private Spinner spinProvince = null;

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

        spinProvince = (Spinner) super.findViewById(R.id.province);
        // 註冊 OnItemSelected 事件
        spinProvince.setOnItemSelectedListener(new ProvOnItemSelectedListener());
    }

    private class ProvOnItemSelectedListener implements OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
            // 取出被選中項目的文字
            String sInfo = adapter.getItemAtPosition(position).toString();
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            String sInfo = "什麼也沒選!";
            Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
        }
    }
}

兩個回呼方法別搞混

onItemSelected() 在使用者挑選項目時觸發,position 就是所選項目的索引,搭配 getItemAtPosition() 就能拿到文字內容。

onNothingSelected() 則是在「完全沒有項目可選」時才被呼叫,例如資料來源被清空。日常開發中它多半是空實作,但介面必須實作,所以不能省略。

三、執行結果

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