android開發中spinner控制項的使用

來源:互聯網
上載者:User

這文章是看完Mars 老師的教學視頻後根據自己理解寫的,所以部分內容引用到Mars 老師視頻。

       ps :極力推薦初學android的朋友看Mars老師的視頻。

 

本文:

        spinner控制項就好比如我們電腦的下拉選擇菜單,但由於手機螢幕的顯示範圍有限,所以就會彈出一個類似於對話方塊的選擇菜單。如:

-------------------------------->

 

 

 

 

第二就是構造spinner控制項的步奏:

          1.在布局檔案中聲明資訊(如ID,寬高背景等)

<spinner   android:"@+id/spinner"   android:layout_wight="fill_parent"   android:layout_height="wrap_content"/>     

         2.在string.xml中聲明一個數組,這個數組是彈出選擇菜單的選項文字

 <string-array name="planets_array">        <item>Mercury</item>        <item>Venus</item>        <item>Earth</item>        <item>Mars</item>        <item>Jupiter</item>        <item>Saturn</item>        <item>Uranus</item>        <item>Neptune</item>    </string-array>

      3.建立一個Arryadapter對象。並調用兩個方法

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,        R.array.planets_array, android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

其中createFromResource方法中有三個參數,分別表示:

      this:內容物件,

      R.array.planets_array:引用在string.xml中聲明的數組;

      android.R.layout.simple_spinner_item:設定主題;

其中setDropDownViewResource
方法是用來設定spinner中每一個選項的主題;

      4.得到一個spinner 對象然後設定對象的資料:

spinner.setaAdapter(adapter);//把上面設定好的adapter傳進spinner中(相當於快顯功能表的內容);spinner.setPrompt("測試");//快顯功能表的描述

第三是設定監聽器來監聽spinner的動作:

class spinnerListener implements OnItemSelectedListener {    ...        public void onItemSelected(AdapterView<?> parent, View view,             int pos, long id) {        // An item was selected. You can retrieve the selected item using        // parent.getItemAtPosition(pos)    }    public void onNothingSelected(AdapterView<?> parent) {        // Another interface callback    }}

OnItemSelectedListener
類中可以複寫兩個函數:

        1.void
onItemSelected :使用者選中了菜單中的某一項後程式要執行的動作(其中傳入參數int pos就是被選中選項在菜單中的位置)

        2.void onNothingSelected :當使用者什麼都沒有選中的情況下要執行的動作;

 

 

 

附加:上面說的是靜態設定選擇菜單中的內容,也就是說菜單中的選中是固定不可變的,但實際應用上很多時候選項是需要隨著使用者的操作而改變的,所以android就有一個動態設定ArrayAdapter的方法:

            過程是先設定一個List<T>的對象,再建立一個ArrayAdapter對象的建構函式:

public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)

傳入四個參數:

       1.context:內容物件;

       2.resource:設定菜單的樣式(就是主題一般為R.layout.item的ID);

       3.textViewResourceId:指定textView空間的ID;

       4.T[] objects:就是上面設定的List對象;

 

                   

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.