-
效果
-
核心代碼
>方法
/** * @description 選擇日期彈出框 * @param listener 選擇日期確定后執行的接口 * @param curDate 當前顯示的日期 * @return * @author wqy * @time 2020-1-6 14:23 */
public void showDatePickDialog(DatePickerDialog.OnDateSetListener listener, String curDate) { Calendar calendar = Calendar.getInstance(); int year = 0,month = 0,day = 0; try { year =Integer.parseInt(curDate.substring(0,curDate.indexOf("-"))) ; month =Integer.parseInt(curDate.substring(curDate.indexOf("-")+1,curDate.lastIndexOf("-")))-1 ; day =Integer.parseInt(curDate.substring(curDate.lastIndexOf("-")+1,curDate.length())) ; } catch (Exception e) { e.printStackTrace(); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day=calendar.get(Calendar.DAY_OF_MONTH); } DatePickerDialog datePickerDialog = new DatePickerDialog(this,DatePickerDialog.THEME_HOLO_LIGHT,listener, year,month , day); datePickerDialog.show(); }
>調用
showDatePickDialog(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { etDate.setText(year + "-" + (month + 1) + "-" + day); } }, etDate.getText().toString());
說明:etDate為一個輸入框EditText 顯示當wujiaox前選擇的日期,也可使用 TextView 。
⭐使用EditText 時需注意:將EditText Touch 時彈出輸入框的效果禁用掉,所以盡量使用 onTouch 來實現彈出,不用 onClick 事件
@Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){ hideInput();//隱藏輸入框
switch (view.getId()) { case R.id.etDate: showDatePickDialog(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { //選擇日期過后執行的事件
etDate.setText(year + "-" + (month + 1) + "-" + day); } }, etDate.getText().toString()); break; } } return false; }
>hideInput方法 有可能不是當前輸入框調出的輸入框,在點擊之前有輸入框也要隱藏掉
/** * 隱藏鍵盤 */
protected void hideInput() { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); View v = getWindow().peekDecorView(); if (null != v) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } }