创建下拉菜单:
1.在局部文件中声明一个Spinners:
<Spinner android:id="@+id/planets_spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" />
2.为Spinners指定一个SpinnerAdapter:
1>在string资源文件中声明一个字符数组:
<?xml version="1.0" encoding="utf-8"?> <resources> <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>
2>在Activity中用A
rrayAdapter填充
spinner:Spinner spinner = (Spinner) findViewById(R.id.spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter);
3>响应用户选择:
在Activity中实现AdapterView.OnItemSelectedListener接口并实现
回调方法。如:onItemSelected()
并绑定到该Spinner中:public class SpinnerActivity extends Activity implements OnItemSelectedListener { ... public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } }
Spinner spinner = (Spinner) findViewById(R.id.spinner); spinner.setOnItemSelectedListener(this);