標籤:android spinner 數值選取器
關鍵區段代碼如下
1、Spinnner
在布局檔案中:
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content" > <Spinner android:id="@+id/sp_select_leave_type" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="85dp" /> </TableRow>
定義對象:
private Spinner mSpinnerSelectLeaveType;//選擇請假類型
獲得對象後綁定監聽事件:
mSpinnerSelectLeaveType.setOnItemSelectedListener(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> parent, View view,int position, long id) {//獲得每項選中的資料mleaveType= getApplicationContext().getResources().getStringArray(R.array.leave_type)[position];}@Overridepublic void onNothingSelected(AdapterView<?> parent) {Toast.makeText(getApplicationContext(), "確認是否正確選擇", 500).show();}});
給spinnner綁定資料關鍵代碼如下:
/**
* 為請假人部門spinner綁定資料
*/
private void setDepartmentAdapter(){
mcontentDepartment=getApplicationContext().getResources().getStringArray(R.array.leave_department);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.spinner_item, mcontentDepartment);
mSpinnerSelectDepartment.setAdapter(adapter);
}
mcontentDepartment=getApplicationContext().getResources().getStringArray(R.array.leave_department);這段代碼是擷取res/values中的strings中擷取對應的資料:
<string-array name="leave_type"> <item >事假</item> <item >婚假</item> <item >病假</item> </string-array>
每個資料顯示的布局:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#f00" android:textSize="15sp" android:padding="10dp" > </TextView>
運行結果:
2、數值選取器
android Spinner和數值選取器使用demo