Spinner下拉菜单
一、Spinner自定义下拉菜单
private Spinner mySpinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
final String[] countriesStr = { "台北市", "台北县", "台中市", "高雄市" };
ArrayAdapter adapter = new ArrayAdapter(this,
R.layout.myspinner, R.id.textView1, countriesStr);
//默认:ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,allCountries);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//右边有radio,可去掉_dropdown
mySpinner = (Spinner) findViewById(R.id.spinner1);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
public void onItemSelected(AdapterView> arg0, View arg1,
int arg2, long arg3) {
toast(countriesStr[arg2]);//toast(arg0.getSelectedItem().toString());
}
public void onNothingSelected(AdapterView> arg0) {
}
});
}
public void toast(String str) {
Toast.makeText(SpinnerNew.this, str, Toast.LENGTH_LONG).show();
}
myspinner.xml
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:id="@+id/linearLayout2"
android:layout_height="wrap_content"
android:background="@color/yellow">
android:id="@+id/imageView1"
android:src="@drawable/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:text="TextView"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black">
二、动态添加和删除选项
/* 将值新增至adapter */
String newCountry = "hello";
adapter.add(newCountry);
int position = adapter.getPosition(newCountry);
mySpinner.setSelection(position);
/* 将选中项从adapter移除 */
adapter.remove(mySpinner.getSelectedItem().toString());