2012-02-29 83 views
4

實現在Android中DatePickerDatePickerDialog容易。但是,當涉及到數據存儲,我有這些類問題:手動輸入

如果您使用微調(+或 - 按鈕)更改日期,一切工作正常。事件「更改日期」或「日期設置」被調用,您可以獲取用戶輸入的值。

但是當一年手動輸入到輸入字段(通過鍵盤)和用戶,然後點擊「保存」對話框中,將不會有任何的事件調用,你就無法得到那個手動輸入值。

當用戶改變與滑塊手動重新輸入後,在今年的東西它纔有效。因爲當你使用滑塊時,事件被觸發。

這是正常的行爲嗎?我該如何實現所需的行爲,即當用戶手動輸入某些內容並點擊「保存」時觸發事件?

在此先感謝!

回答

8

就明確的重點,而Android將手動輸入設置的數字

例如:。

DatePicker datePicker = fidnViewById(R.id.dp); 

當像onClick()那樣保存時,添加 datePicker.clearFocus();

這必須工作。

+0

它的工作原理就像一個魅力!謝謝內 – 2015-05-22 06:24:19

0

如果您查看Date Picker Example,只要用戶單擊對話框上的「SET」按鈕,就會收到DatePickerDialog.OnDateSetListener回調。

看一下對話框下方

enter image description here

即使你使用鍵盤輸入日期,日期本身不被接受,直到你單擊該對話框中的「設置」按鈕,即當DatePickerDialog.OnDateSetListener回調被稱爲

1

我有同樣的問題,接受的答案真的幫了我很多。我的情況有點不同,但我使用的是DatePickerDialog。以下是DatePicker最終如何正常工作。

首先聲明變量,然後定義它們。

private DatePickerDialog.OnDateSetListener date; 
private DatePickerDialog mDatePickerDialog; 
private Calendar myCalendar; 

// Get the calendar instance 
myCalendar = Calendar.getInstance(); 

// Define the date set listener first. 
date = new DatePickerDialog.OnDateSetListener() { 
    @Override 
    public void onDateSet(DatePicker view, int year, int monthOfYear, 
     int dayOfMonth) { 
     // Do something with year, monthOfYear and dayOfMonth 
    } 
}; 

// Now define the DatePickerDialog 
mDatePickerDialog = new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)); 
mDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Set", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface arg0, int arg1) { 
     DatePicker datePicker = mDatePickerDialog.getDatePicker(); 

     // The following clear focus did the trick of saving the date while the date is put manually by the edit text. 
     datePicker.clearFocus(); 
     date.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()); 
    } 
}); 

然後一個按鈕的onClick

mDatePickerDialog.show();