2012-12-18 19 views
0

是否有一個取消/設置選項代替單個設置命令的日期/時間選擇器?我的用例是,當我點擊日期選擇器,並且該字段不是強制性的,我可能想要清除選定的值。我的代碼看起來是這樣的:在android中的取消選項的日期選擇器

private DatePickerDialog datePicker = null; 

datePicker = new DatePickerDialog(getContext(), new DateSetListener(), year, monthOfYear, dayOfMonth); 
+0

沒試過,但應該對可能這需要擴展取消按鈕,並在此實現您自己的取消按鈕功能 –

+1

Android上的標準是按系統後退按鈕以取消對話框 - 監聽器不會被觸發。 – ataulm

+0

@ataulm即使我這樣做,選定的日期不會被清除。 – lokoko

回答

0

DatePickerDialog和TimePickerDialog存在問題(問題#34833)。我們可以使用計數器作爲解決方案來擺脫此問題。

2

我會用一個簡單的對話框,並在其中包含一個DateTimePicker和設置和取消按鈕或功能的任何其他的國王,你想包括

另一個UI /您可以實現的X解決方案是按需顯示DateTimePicker(例如,用戶單擊按鈕)

0

我知道它的後期解決方案(我不想在這任何一個浪費時間),這可能是這樣。(感謝https://stackoverflow.com/users/642161/dmon

import android.app.DatePickerDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.widget.DatePicker; 

import java.lang.reflect.Field; 

/** 
* Created by root on 12/8/15. 
*/ 
public class DatePickerDialogFragment extends DatePickerDialog { 

public DatePickerDialogFragment(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { 
    super(context, null, year, monthOfYear, dayOfMonth); 
    initializePicker(callBack); 
} 

public DatePickerDialogFragment(Context context,int theme,OnDateSetListener callBack,int year, int monthOfYear, int dayOfMonth) 
{ 
    super(context, theme, null, year, monthOfYear, dayOfMonth); 
    initializePicker(callBack); 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setCancelable(false); 
} 

@Override 
public void onBackPressed() { 
    super.onBackPressed(); 
    dismiss(); 

} 

private void initializePicker(final OnDateSetListener callback) { 
    try { 
     //If you're only using Honeycomb+ then you can just call getDatePicker() instead of using reflection 
     Field pickerField = DatePickerDialog.class.getDeclaredField("mDatePicker"); 
     pickerField.setAccessible(true); 
     final DatePicker picker = (DatePicker) pickerField.get(this); 
     this.setButton(DialogInterface.BUTTON_NEGATIVE, getContext().getText(android.R.string.cancel), (OnClickListener) null); 
     this.setButton(DialogInterface.BUTTON_POSITIVE, getContext().getText(android.R.string.ok), 
       new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         picker.clearFocus(); //Focus must be cleared so the value change listener is called 
         callback.onDateSet(picker, picker.getYear(), picker.getMonth(), picker.getDayOfMonth()); 
        } 
       }); 
    } catch (Exception e) { /* Reflection probably failed*/ } 
} 
} 
相關問題