Android ApiDemos示例解析(192):Views->Spinner

Spinner為下拉框,為AdapterView的子類。AdapterView的顯示可以通過數據綁定來實現,數據源可以是數組或是數據庫記錄,數據源和AdapterView是通過Adapter作為橋梁。通過Adapter,AdatperView可以顯示數據源或處理用戶選取事件,如:選擇列表中某項。

本例Adapter 使用的是ArrayAdapter,可以參見Android ApiDemos示例解析(168):Views->Lists->1. Array

並為Spinner 添加事件處理:

[java] view plaincopyprint?
Spinner s1 = (Spinner) findViewById(R.id.spinner1); 
 ArrayAdapter<CharSequence> adapter 
 = ArrayAdapter.createFromResource( 
 this, R.array.colors, 
 android.R.layout.simple_spinner_item); 
 adapter.setDropDownViewResource(android.R 
   .layout.simple_spinner_dropdown_item); 
 s1.setAdapter(adapter); 
 s1.setOnItemSelectedListener( 
 new OnItemSelectedListener() { 
 public void onItemSelected( 
 AdapterView<?> parent, 
 View view, int position, long id) { 
 showToast("Spinner1: position="  
       + position + " id=" + id); 
 } 
 
 public void onNothingSelected(AdapterView<?> parent) { 
 showToast("Spinner1: unselected"); 
 } 
 }); 

Spinner s1 = (Spinner) findViewById(R.id.spinner1);
 ArrayAdapter<CharSequence> adapter
 = ArrayAdapter.createFromResource(
 this, R.array.colors,
 android.R.layout.simple_spinner_item);
 adapter.setDropDownViewResource(android.R
   .layout.simple_spinner_dropdown_item);
 s1.setAdapter(adapter);
 s1.setOnItemSelectedListener(
 new OnItemSelectedListener() {
 public void onItemSelected(
 AdapterView<?> parent,
 View view, int position, long id) {
 showToast("Spinner1: position="
       + position + " id=" + id);
 }

 public void onNothingSelected(AdapterView<?> parent) {
 showToast("Spinner1: unselected");
 }
 });

 

 

 

You May Also Like