TimePicker hour doesn't update after switching to 24h

纵然是瞬间 提交于 2019-12-05 10:42:41

I can use timePicker.setCurrentHour(new Date().getHours()), but that's not the solution I want. It should be possible to solve it in a better way.

Looking at the source code, this is a bug that appeared sometime after API 10:

public void setIs24HourView(Boolean is24HourView) {
    if (mIs24HourView == is24HourView) {
        return;
    }
    mIs24HourView = is24HourView; 
    // cache the current hour since spinner range changes
    int currentHour = getCurrentHour();
    updateHourControl();
    // set value after spinner range is updated
    setCurrentHour(currentHour);
    updateAmPmControl();
}

The correct order is:

// cache the current hour since spinner range changes
int currentHour = getCurrentHour();
mIs24HourView = is24HourView;

Because getCurrentHour() relies on mIs24HourView to return 1-12 or 0-23...

But until the source code is updated and deployed, you don't have much of a choice. You need to call setCurrentHour() after setIs24HourView() yourself.

you should initialize your dialog in onCreate

In addition to the accepted answer, if you are using Xamarin then you can do the same thing by subclassing the TimePicker and overriding SetIs24HourView like so:

public class TwentyFourHourMvxTimePicker : MvxTimePicker
{
    public TwentyFourHourMvxTimePicker(Context context, IAttributeSet attrs) : base (context, attrs)
    {

    }

    public override void SetIs24HourView (Java.Lang.Boolean is24HourView)
    {
        var current = CurrentHour;
        base.SetIs24HourView(is24HourView); 
        CurrentHour = current;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!