Spinner_demo.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" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="被选中的人名显示在下面"
android:textSize="25sp"
/>
</LinearLayout>
ASpinner
package com.example.uidemo3;
import java.util.ArrayList;
import android.R.anim;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class ASpinner extends Activity {
Spinner spinner1;
ArrayList<String> arrayList = new ArrayList<String>();
TextView textView1;
OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {
/*
* parent The AdapterView where the selection happened
*view The view within the AdapterView that was clicked
*position The position of the view in the adapter
*id The row id of the item that is selected
*
*AdapterView<?>代表Spinner
*View代表Spinner里面的item
*/
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
textView1.setText( ((TextView)view).getText());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.spinner_demo);
spinner1 = (Spinner) this.findViewById(R.id.spinner1);
textView1 = (TextView) this.findViewById(R.id.textView1);
arrayList.add("小仓优子");
arrayList.add("苍井空");
arrayList.add("松岛枫");
arrayList.add("波多野结衣");
arrayList.add("樱田樱");
arrayList.add("小峰由衣");
arrayList.add("早乙女");
arrayList.add("小泉彩");
// 适配的概念Adapter,主要负责适配数据和各种样式
// 下拉菜单的样式
@SuppressWarnings({ "unchecked", "rawtypes" })
ArrayAdapter arrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, arrayList);
// 以下显示的是一行,只有一行能看的见
// arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// 这种是带有文本和radio的下拉效果。
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
// 为下拉的spinner设置内容
spinner1.setAdapter(arrayAdapter);
//为spinner1设置监听事件
spinner1.setOnItemSelectedListener(onItemSelectedListener);
}
}