Android入门逆引手册 - 11 Spinner(Spinner)的使用
这里介绍android.widget.Spinner类的使用。
● Adapter的设置,调用setAdapter()方法。
● 追加Item选择时间的处理,调用setOnItemSelectedListener()方法,并把AdapterView.OnItemSelectedListener实例作为参数传递过去。
例程源码(Java)
01.
ArrayAdapter<String> adapter =
new
ArrayAdapter<String>(
02.
this
,
03.
android.R.layout.simple_spinner_item);
04.
05.
adapter.setDropDownViewResource(
06.
android.R.layout.simple_spinner_dropdown_item);
07.
08.
adapter.add(
"red"
);
09.
adapter.add(
"green"
);
10.
adapter.add(
"blue"
);
11.
12.
Spinner spinner = (Spinner) findViewById(id.spinner);
13.
14.
spinner.setAdapter(adapter);
15.
16.
spinner.setOnItemSelectedListener(
new
OnItemSelectedListener() {
17.
@Override
18.
public
void
onItemSelected(
19.
AdapterView<?> parent,
20.
View view,
21.
int
position,
22.
long
id) {
23.
Spinner spinner = (Spinner) parent;
24.
Log.v(
"Test"
,
"id = "
+ id +
"("
25.
+ spinner.getSelectedItem().toString() +
")"
);
26.
}
27.
@Override
28.
public
void
onNothingSelected(AdapterView<?> parent) {
29.
}
30.
});
例程源码(Resource)
1.
<
Spinner
android:id
=
"@+id/spinner"
2.
android:layout_height
=
"wrap_content"
3.
android:layout_width
=
"fill_parent"
/>
参考资源
● Spinner | Android Developers
● ArrayAdapter | Android Developers
● R.layout | Android Developers