android學習筆記19————–Spinner 下拉列表的用法

Spinner相當HTML的下拉列表,下面我們實現一個在註冊中選擇血型的例子:
      首先在string.xml寫一個string的集合,string.xml這個文件主要是放一些文字信息的

比如驗證內容,要顯示的文字等,定義這個集合的代碼如下:

          <?xml version="1.0" encoding="utf-8"?>
          <resources>
             <string name="hello">Hello World, registActivity!</string>
            <string name="app_name">註冊</string>
                <string name="xuexing">血 型:</string>
                <string-array name="xuexings">
                <item>A</item>
               <item>B</item>
               <item>O</item>
               <item>AB</item>
                </string-array>
</resources>

然後是在main.xml中寫如下內容:

           <Spinner
            android:id="@+id/s1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:prompt="@string/xuexing"
            >
           </Spinner>

 

 import android.app.Activity;   
import android.os.Bundle;   
import android.view.View;   
import android.widget.AdapterView;   
import android.widget.AdapterView.OnItemSelectedListener;   
import android.widget.ArrayAdapter;   
import android.widget.Spinner;   
import android.widget.Toast;   
     
public class MainHelloSpinner extends Activity  
{   
    @Override  
     public void onCreate(Bundle savedInstanceState)  
     {   
         super.onCreate(savedInstanceState);   
         setContentView(R.layout.main);   
   
         //找到Xml中定義的下拉列表    
         Spinner spinner = (Spinner)findViewById(R.id.s1);   
 
         //準備一個數組適配器    
         ArrayAdapter adapter = ArrayAdapter.createFromResource(   
                 this, R.array.xuexings, android.R.layout.simple_spinner_item);   
 
         //設置下拉樣式  android裡面給大傢提供瞭豐富的樣式和功能圖片   
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   
 
         //為下拉列表設置適配器    
         spinner.setAdapter(adapter);   
 
         //定義子元素選擇監聽器    
         OnItemSelectedListener oisl=  new OnItemSelectedListener()  
        {   
             @Override  
             public void onItemSelected(AdapterView<?> parent, View view, int position, long id)  
             {   
                   Toast.makeText(MainHelloSpinner.this,"選擇的血型:" +   
                   parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();     
             }   
             @Override  
             public void onNothingSelected(AdapterView<?> parent) {}   
         };   
         //為下拉列表綁定事件監聽器    
         spinner.setOnItemSelectedListener(oisl);   
     }   
 
 }  
 

摘自 奔跑的蝸牛

發佈留言