Spinner組件學習筆記

        Spinner是一個列表選項,相當於彈出一個菜單供用戶選擇。 SpinnerGallery都繼承了AbsSpinnerAbsSpinner繼承了AdapterView因此它也表現出AdapterView的特徵:只要爲AdapterView提供Adapter即可。

       如果開發者使用Spinner時已經可以確定下來列表框裏的列表項,則完全不需要寫代碼,只要爲Spinner指定android:entries屬性即可實現Spinner,如果需要在運行時動態的決定Spinner的列表項,或程序需要對Spinner的列表項進行定製,則可使用AdapterSpinner提供列表項。

XML代碼:

第一個Spinner組件指定了android:entries屬性,第二個Spinner組件沒有指定,因此需要在Activity中爲它設置Adapter。

<?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組件,
	指定該顯示該Spinner組件的數組 -->
<Spinner
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:entries="@array/books" 
	android:prompt="@string/tip"
	/>
 <Spinner
    android:id="@+id/spinner"
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content"
	android:prompt="@string/tip"
	/>
</LinearLayout>

java代碼:

public class MainActivity extends Activity{
    
	 Spinner spinner;
	 @Override
     public void onCreate(Bundle savedInstanceState){
	    super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		spinner = (Spinner)findViewById(R.id.spinner);
		String[] str = {"孫悟空","豬八戒","牛魔王"};
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_list_item_multiple_choice, str);
		// 爲Spinner設置Adapter
		spinner.setAdapter(adapter);
		
     }
}

顯示結果:


發佈了33 篇原創文章 · 獲贊 5 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章