在Android App应用中,OnItemSelectedListener事件也会经常用到,我们一起来了解一下。
基本知识点:OnItemSelectedListener事件
一、界面
1、新建province.xml件。
在“res/values”位置新建province.xml文件。
(1)province.xml文件位置如下图所示:
(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、最终效果如下: