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.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Spinner spinner ;
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spinner1);
//动态创建spinner的数据,需要一个xml布局作为模板
List<String> list = new ArrayList<String>();
list.add("test1");
list.add("test2");
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item,
R.id.textView1, list);
// 静态添加固定数据,通过createFromResource()创建一个ArrayAdapter
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
// this, R.array.spinner, android.R.layout.simple_spinner_item);
// 设置spinner每个条目的样式,此处引用android系统自带的文件
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 将适配器加入spinner
spinner.setAdapter(adapter);
// 标题的
spinner.setPrompt("测试");
spinner.setOnItemSelectedListener(new spinnerListenner());
}
class spinnerListenner implements OnItemSelectedListener{
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// 的到被选中控件的内容
String selectString = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
<resources>
<string name="hello">Hello World, MainActivity!</string>
<string name="app_name">SpinnerDemo</string>
<string-array name="spinner">
<item>张三</item>
<item>李四</item>
<item>王五</item>
<item>牧六</item>
</string-array>
</resources>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Spinner android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/spinner1"></Spinner>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp" android:textColor="#000000"></TextView>
</LinearLayout>