android Spinner和數值選擇器使用demo
阿新 • • 發佈:2019-02-07
關鍵部分程式碼如下
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() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { //獲得每項選中的資料 mleaveType= getApplicationContext().getResources().getStringArray(R.array.leave_type)[position]; } @Override public 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、數值選擇器