在Android中取消选项的日期选择器

时间:2012-12-18 11:46:49

标签: android android-datepicker

是否可以使用取消/设置选项代替单个Set命令的日期/时间选择器。我的用例是,当我点击日期选择器并且该字段不是必需的时,我可能想清除所选的值。我的代码看起来像这样:

private DatePickerDialog datePicker = null;

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

3 个答案:

答案 0 :(得分:2)

我会使用一个简单的Dialog,其中包括一个DateTimePicker和SET和CANCEL按钮或任何其他你想要包含的功能之王

您可以实现的另一个UI / X解决方案是按需显示DateTimePicker(例如,用户单击按钮)

答案 1 :(得分:0)

DatePickerDialog和TimePickerDialog存在问题(问题#34833)。我们可以使用计数器来解决这个问题。

答案 2 :(得分: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*/ }
}
}