第21章、OnItemSelectedListener事件(从零开始学Android)

   在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、最终效果如下:

  

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋会全

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值