如何在Spinner模式下为Android 7.0修复DatePickerDialog?

时间:2018-07-20 18:37:39

标签: java android calendar android-datepicker

我目前正在开发一个简单的项目,该项目包含一个包装成Web视图的网站,并进行了少量交互,以改善网站本身与android移动设备之间的互动。

由于该网站包含用户生日的日期输入字段,因此我一直希望实现一种与所有设备兼容的微调器格式的日期选择器。 我尝试实施以下解决方案:

`<style name="MyAppTheme" parent="android:Theme.Material">
    <item name="android:dialogTheme">@style/MyDialogTheme</item>
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>
<style name="MyDialogTheme" parent="android:Theme.Material.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePicker</item>
</style>
<style name="MyDatePicker" parent="android:Widget.Material.DatePicker">
    <item name="android:datePickerMode">spinner</item>
</style>`

如图所示: Datepicker dialog without calendar visualization in lollipop [spinner mode]?

但是,正如答案所指出的,由于以下已知错误,该解决方案不适用于Android 7.0牛轧糖/ API 24:https://issuetracker.google.com/issues/37119315

做一些研究时,我遇到了一些建议的解决方案,例如:

https://gist.github.com/uqmessias/d9a8dc624af935f344dfa2e8928490ec

https://gist.github.com/lognaturel/232395ee1079ff9e4b1b8e7096c3afaf

DatePickerDialog Holo styling failed on Android 7 Nougat

但是,就我而言,它们似乎都不适用于装有Android 7.0的设备或任何其他设备。

我在android开发方面经验不足,所以我想知道是什么原因引起的,以及如何解决它,因为一些解决方案一直保持到最近,而这些解决方案几乎已经废弃了。 / p>

我是否需要实现我发布的代码中没有指出但我不知道的东西?

是不是直接从Web视图而不是从应用程序本身调用datepicker元素,这使这些解决方案对我毫无用处?如果是这样,是否有任何解决方法?

3 个答案:

答案 0 :(得分:1)

我遇到了同样的问题(用户不想逐月向后滚动40年来查找自己的出生年份,而且大多数人都不知道您可以在android日期选择器中单击年份来滚动多年)。像您一样,我无法让微调器普遍运行,因此我(在SO和Google的帮助下)弄清楚了如何使它开始于年份选择模式。

我的DatePickerDialogFragment的代码粘贴在下面。

public class DatePickerDialogFragment extends DialogFragment {

    private DatePickerDialog.OnDateSetListener listener = null;

    void setListener(DatePickerDialog.OnDateSetListener listener) {
        this.listener = listener;
    }

    private static final String START_IN_YEARS = "com.myapp.picker.START_IN_YEARS";
    private static final String YEAR = "com.myapp.picker.YEAR";
    private static final String MONTH = "com.myapp.picker.MONTH";
    private static final String DAY_OF_MONTH = "com.myapp.picker.DAY_OF_MONTH";

    public static DatePickerDialogFragment newInstance(boolean startInYears, Calendar c) {
        DatePickerDialogFragment f = new DatePickerDialogFragment();

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        Bundle args = new Bundle();
        args.putBoolean(START_IN_YEARS, startInYears);
        args.putInt(YEAR, year);
        args.putInt(MONTH, month);
        args.putInt(DAY_OF_MONTH, day);

        f.setArguments(args);
        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        Bundle args = getArguments();
        DatePickerDialog dpd = null;

        if( listener != null && args != null) {
            boolean startInYears = args.getBoolean(START_IN_YEARS);

            Context context = getActivity();
            boolean requireSpinnerMode = isBrokenSamsungDevice();
            if (requireSpinnerMode) {
                context = new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog);
            }

            int year = args.getInt(YEAR);
            int month = args.getInt(MONTH);
            int day = args.getInt(DAY_OF_MONTH);

            dpd = new DatePickerDialog(context, listener, year, month, day);

            if (startInYears && !requireSpinnerMode) {
                boolean canOpenYearView = openYearView(dpd.getDatePicker());
                if (!canOpenYearView) {
                    context = new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog);
                    dpd = new DatePickerDialog(context, listener, year, month, day);
                }
            }
        }
        else {
            setShowsDialog(false);
            dismissAllowingStateLoss();
        }

        return dpd;
    }

    private static boolean isBrokenSamsungDevice() {
        return Build.MANUFACTURER.equalsIgnoreCase("samsung") &&
                isBetweenAndroidVersions(
                        Build.VERSION_CODES.LOLLIPOP,
                        Build.VERSION_CODES.LOLLIPOP_MR1);
    }

    private static boolean isBetweenAndroidVersions(int min, int max) {
        return Build.VERSION.SDK_INT >= min && Build.VERSION.SDK_INT <= max;
    }

    private static boolean openYearView(DatePicker datePicker) {
        if( isBrokenSamsungDevice() ) {
            return false;
        }
        try {
            Field mDelegateField = datePicker.getClass().getDeclaredField("mDelegate");
            mDelegateField.setAccessible(true);
            Object delegate = mDelegateField.get(datePicker);
            Method setCurrentViewMethod = delegate.getClass().getDeclaredMethod("setCurrentView", int.class);
            setCurrentViewMethod.setAccessible(true);
            setCurrentViewMethod.invoke(delegate, 1);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

Activity中的代码(onCreate中的成员变量和内容)启动该代码(并在旋转时保留),如下所示:

// Class member variables
private Calendar myCalendar = Calendar.getInstance();
private boolean birthday_is_set = false;


// this next part is in onCreate

// set the calendar date to a saved date if applicable
// and change birthday_is_set if they had saved a birthday


final DatePickerDialog.OnDateSetListener birthdayListener = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {
        // I save the date in a calendar, replace this
        // with whatever you want to do with the selected date
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        birthday_is_set = true;
        updateBirthdayLabel();
    }
};

if (savedInstanceState != null) {
    DatePickerDialogFragment dpf;

    dpf = (DatePickerDialogFragment) getFragmentManager().findFragmentByTag("birthdayDatePicker");
    if (dpf != null) {
        // on rotation the listener will be referring to the old Activity,
        // so we have to reset it here to act on the current Activity
        dpf.setListener(birthdayListener);
    }
}

birthdayDatePicker.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Your logic may vary here. I chose not to start it in year
        // mode if they've already selected a date.
        boolean startInYears = !birthday_is_set;
        DatePickerDialogFragment dpf = DatePickerDialogFragment.newInstance(startInYears, myCalendar);
        dpf.setListener(birthdayListener);
        dpf.show(getFragmentManager(), "birthdayDatePicker");
    }
});

这既包括使它以年模式启动的黑客,也包括对某些老式三星设备上某些随机日期选择器故障的修复。该版本已经运行了几个月,没有崩溃或用户抱怨API 15 +。

答案 1 :(得分:0)

对于有兴趣使WebView中的DatePicker正常工作而无需添加JS接口来手动调用您自己的DatePicker的任何人,以下解决方案可以覆盖您应用中的所有DatePickers:

https://github.com/Noisyfox/DatePickerForceSpinner

此修复程序也适用于LayoutInflater创建的任何DatePicker,因此您不必担心更改现有的布局文件。

答案 2 :(得分:0)

readlines()
This will be displayed in a monospaced font. The first four spaces
will be stripped off, but all other whitespace will be preserved.

要创建不是块而是内联代码范围,请使用反引号:

Markdown and HTML are turned off in code blocks: <i>This is not italic</i>, and [this is not a link](https://example.com) 字符只是$的快捷方式。 如果要在列表中包含预格式化的块,请缩进八个空格:

  1. 这是普通文本。
  2. 这也是,但是现在跟随一个代码块:

    window.jQuery