xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="#ff0000"/>
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
java文件:
监听器的实现方式1——通过接口实现:
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemSelectedListener{
private TextView textView;
//首先还是先声明这个Spinner控件
private Spinner spinner;
//定义一个String类型的List数组作为数据源
private List<String> list;
//定义一个ArrayAdapter适配器作为spinner的数据适配器
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview1);
spinner = (Spinner) findViewById(R.id.spinner);
textView.setText("您选择的城市是:");
//为dataList赋值,将下面这些数据添加到数据源中
list = new ArrayList<String>();
list.add("北京");
list.add("上海");
list.add("深圳");
list.add("广州");
/*为spinner定义适配器,也就是将数据源存入adapter,这里需要三个参数
1. 第一个是Context(当前上下文),这里就是this
2. 第二个是spinner的布局样式,这里用android系统提供的一个样式
3. 第三个就是spinner的数据源,这里就是dataList*/
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
//为适配器设置下拉列表下拉时的菜单样式
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//为spinner绑定我们定义好的数据适配器
spinner.setAdapter(adapter);
//spinner设置监听器
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String cityName=adapter.getItem(arg2);
textView.setText("您选择的城市是:"+cityName);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
监听器的实现方式2——匿名内部类:
//为spinner绑定监听器,这里我们使用匿名内部类的方式实现监听器
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textView.setText("您当前选择的是:"+adapter.getItem(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText("请选择您的城市");
}
});
实现效果: