天天看點

第21章、OnItemSelectedListener事件(從零開始學Android)

   在Android App應用中,OnItemSelectedListener事件也會經常用到,我們一起來了解一下。

  基本知識點:OnItemSelectedListener事件

一、界面

   1、建立province.xml件。

  在“res/values”位置建立province.xml檔案。

  (1)province.xml檔案位置如下圖所示:

  

第21章、OnItemSelectedListener事件(從零開始學Android)

  (2)province.xml内容如下:  

  

第21章、OnItemSelectedListener事件(從零開始學Android)

  (3)代碼  

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

  2、打開“res/layout/activity_main.xml”檔案。

   (1)分别從工具欄向activity拖出1個下拉清單框Spinner。控件來自Form Widgets。

  

第21章、OnItemSelectedListener事件(從零開始學Android)

  (2)打開activity_main.xml檔案。  

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://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、界面如下

  

第21章、OnItemSelectedListener事件(從零開始學Android)

二、OnItemSelectedListener事件 

  1、打開“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 {
	//聲明Spinner對象
	private Spinner spinProvince=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//擷取Spinner
		spinProvince=(Spinner)super.findViewById(R.id.province);
		//注冊OnItemSelected事件
		spinProvince.setOnItemSelectedListener(new ProvOnItemSelectedListener());
		}

	//OnItemSelected監聽器
	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();
			
		}
	}
}
           

  2、最終效果如下:

  

第21章、OnItemSelectedListener事件(從零開始學Android)