2015年5月11日 星期一

【Android】如何使用Spinner(下拉式選單)

原始碼 github  -> https://github.com/markcoolhu/spinnerDemo


1. 先在xml先宣告一個Spinner


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Spinner  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/mySpinner"
    />
</LinearLayout>



2. 接著初始化Spinner



private Spinner spinner;                                                                      
private ArrayAdapter<String> arrayList;                                                       
private Context mContext;          
   
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   mContext = this.getApplicationContext();
   spinner = (Spinner)findViewById(R.id.mySpinner); 
}




3. 宣告一個陣列, 是你想要放進去Spinner理面的資料


private String[] lunch = {"00001", "00002", "00003"};

4. 然後使用ArrayAdapter把它指定給Spinner




private String[] stringData = {"00001", "00002", "00003"};


arrayList = new ArrayAdapter<String>(SpinnerDemo.this,
            android.R.layout.simple_spinner_item, stringData);
spinner.setAdapter(arrayList);


5. Spinner 加入事件


spinner.setOnItemSelectedListener(new OnItemSelectedListener(){

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
       Toast.makeText(mContext, "你選的是"+lunch[position], Toast.LENGTH_SHORT).show();
                
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
       // TODO Auto-generated method stub
    }
});


沒有留言:

張貼留言