Android開發系列(二十一):Spinner的功能和使用方法以及實現列表選擇框


Spinner是一個列表選擇框。相當於彈出一個菜單供用戶進行選擇。

Spinner繼承AdapterView


Spinnet支持的XML的屬性:

android:entries:使用數組資源設置該下拉列表框的列表項目

android:popupBackground:設置下拉列表框的背景色

(一般這兩個比較經常使用一點)


用Spinner用兩種方法:

第一、已經確定下拉列表里的列表項,僅僅要為Spinner指定android:entries屬性就能夠實現Spinner。

第二、假設程序須要在執行時動態地確定下拉列表的內容,或程序須要對下拉列表的下拉項進行定制,能夠使用Adapter為Spinner提供列表項。

下邊,我們把這兩種方式都演示一下。


首先,我們先創建一個Android項目,然后我們在main.xml中配置:

<?

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" /> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>

注意,第一個Spinner用到了android:entries屬性。第二個沒實用到。


由於第一個用到了android:entries="@array/books"這個屬性,所以我們須要在res/values里邊創建個arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="books">
		<item>百度</item>
		<item>阿里巴巴</item>
		<item>騰訊</item>
	</string-array>
 </resources>


在配置好了之后,我們要在主程序中寫java代碼了:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;


public class SpinnerTest extends Activity
{
	Spinner spinner;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 獲取界面布局文件里的Spinner組件
		spinner = (Spinner) findViewById(R.id.spinner);
		String[] arr = { "孫悟空", "豬八戒", "唐僧" };
		// 創建ArrayAdapter對象
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
			android.R.layout.simple_list_item_multiple_choice, arr);
		// 為Spinner設置Adapter
		spinner.setAdapter(adapter);
	}
}
在上邊的代碼中。我們使用一個String數組arr,然后使用ArrayAdapter適配器生成一個Adapter對象,然后為spinner設置這個Adapter


這就是兩種方法。下邊我們看下效果圖吧:






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM