功能上大致与ListView 不做赘述
java 文件
package com.example.spiner;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
publicclass MainActivity extends Activity {
TextView selection;
Spinner spin;
String[] items={"a","b","c","e"};
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//加载视图文件,类似于C#的窗体设计
selection=(TextView)findViewById(R.id.selection);
//查找对应xml文件中的部件
spin=(Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> aa=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,items);
//定义一个数组适配器《string》类型的,
//对应的三个参数分别为 所有者,外观样式,数据源
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//定义下拉列表样式
spin.setAdapter(aa);
//定义适配器
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//定义下拉事件,先打入 new AdapterView.OnItemSelectedListener()后,会提示是否自动生成对应的代码
@Override
publicvoid onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
selection.setText(parent.getItemAtPosition(position).toString());
}
@Override
publicvoid onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
selection.setText("nothing select");
}
});
}
}
xml文件
<LinearLayout 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"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/selection"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>