调用setOnItemSelectedListener()方法,处理下拉列表框被选择事件,把AdapterView.OnItemSelectedListener实例作为参数传入
主界面设计:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Spinner android:id="@+id/spinner"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
下拉列表框每一项的界面样式:stylespinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contentTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#F4FDFF"
/>
代码处理:
public class SpinnerActivity extends Activity {
private static final String TAG = "SpinnerActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
//第二个参数为layout文件在R文件的id,第三个参数为TextView在layout文件的id
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.stylespinner, R.id.contentTextView);
adapter.add("Android");
adapter.add("Symbian");
adapter.add("Iphone");
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Spinner spinner = (Spinner)adapterView;
String itemContent = (String)adapterView.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> view) {
Log.i(TAG, view.getClass().getName());
}
});
}
}