標籤:
Spinner提供了一個快速的方式從集合中選擇值。在預設狀態下,一個Spinner顯示的是當前選擇的值。觸摸Spinner會顯示一個下拉式功能表,使用者可以從中選擇一個值。今天我們就開始Spinner的學習。
項目結構如下:
在xml檔案中定義一個spinner,如下:
<Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" />
在Spinner中增加一個挑選清單,你需要在你的Activity或者Fragment代碼中指定一個SpinnerAdapter。
在Spinner中增加一個挑選清單
Spinner中的列表內容可以來自任何來源,但是需要一個SpinnerAdapter,比如如果選擇內容是一個數組,那麼Adapter是ArrayAdapter,再或者選擇內容來自於資料庫查詢,那麼Adapter是CursorAdapter。
例如如果選擇內容是預先確定的,你可以在string的資源檔中指定一個array內容。
<?xml version="1.0" encoding="utf-8"?><resources> <string-array name="spinner_array"> <item>Linux</item> <item>Huhx</item> <item>LiuLi</item> <item>ChenHui</item> <item>Android</item> </string-array></resources>
在Activity或者Fragment中提供一個ArrayAdapter的執行個體,如下:
spinner = (Spinner) findViewById(R.id.spinner);ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_array, android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);spinner.setAdapter(adapter);
createFromResource方法允許你從一個字元數組中建立一個ArrayAdapter。第二個參數是在資源檔中定義的數組,第三個參數是定義spinner選擇的方式。simple_spinner_item.xml如下:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" style="?android:attr/spinnerItemStyle" android:singleLine="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:textAlignment="inherit"/>
然後你需要調用setDropDownViewResource方法去指定spinner列表中的布局:support_simple_spinner_dropdown_item.xml如下:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" style="?attr/spinnerDropDownItemStyle" android:singleLine="true" android:layout_width="match_parent" android:layout_height="?attr/dropdownListPreferredItemHeight" android:ellipsize="marquee"/>
響應使用者選擇spinner的事件
當使用者在下拉式功能表中選擇一行,Spinner對象接收一個on-item-selected事件:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.i(TAG, "viewa: " + view + ", parent: " + parent + ", position: " + position + ", id: " + id); } @Override public void onNothingSelected(AdapterView<?> parent) { Log.i(TAG, "on nothing selected"); }});
運行效果如下:
android基礎---->Spinner的使用