Android docs中的范例,简单翻译整理如下。
注:范例过程及相关代码有部分调整,请知晓。
--------------------------------------------
1、创建新项目,名称HelloSpinner;
2、修改res/layout/strings.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="planet_prompt">Choose a planet</string>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
3、修改res/layout/main.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="@string/planet_prompt"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/planet_prompt"
/>
</LinearLayout>
3、增加类MyOnItemSelectedListener.java,类代码如下:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Toast.makeText(parent.getContext(), "The planet is " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
4、修改HelloSpinner.java的onCreate方法,内容如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
5、运行项目,即可看到运行效果,如下图所示: