在Android App應用中,OnItemSelectedListener事件也會經常用到,我們一起來了解一下。
基本知識點:OnItemSelectedListener事件
一、界面
1、建立province.xml件。
在“res/values”位置建立province.xml檔案。
(1)province.xml檔案位置如下圖所示:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZwpmL0MTOy8FO4AzM5gDN1MTMvw1Nw8CXyEjMxAjMvw1ckF2bsBXdvwFdl5mLuR2cj5Set1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
(2)province.xml内容如下:
(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。
(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、界面如下
二、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、最終效果如下: