Android下拉列表(Spinner)例子

下拉列表(Spinner)的例子,首先要在layout中拖放一个Spinner,例子中的ID为Spinner01

<Spinner android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_y="132dip" android:layout_x="97dip" android:id="@+id/Spinner01"></Spinner>

代码:

/*
 	ArrayAdapter.createFromResource参数解析:
 	第一个是Context,
 	第二个(R.array.colors)是数据来源,在values.xml,内容为
		<?xml version="1.0" encoding="utf-8"?>
		<resources>
			<string-array name="colors">
				<item>red</item>
				<item>blue</item>
				<item>green</item>
				<item>yellow</item>
				<item>black</item>
			</string-array>
		</resources>
		第三个(android.R.layout.simple_spinner_item)为显示的样式
 */
Spinner spinner = (Spinner) findViewById(R.id.Spinner01);
//建立方法有两种
//方法一,从xml读取
//ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.colors, android.R.layout.simple_spinner_item);

//方法二,使用数组
CharSequence[] seq = {"test11","test12","test13","test14","test15"};
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, seq);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			//showToast("Spinner1: position=" + position + " id=" + id);
			//选择后
		}
		public void onNothingSelected(AdapterView<?> arg0) {
			//showToast("没有选择");
			//没有选择
		}
	});
updatedupdated2024-08-302024-08-30