Android TimePicker AM/PM button not invoking onTimeChanged

前端 未结 11 1126
半阙折子戏
半阙折子戏 2021-02-05 12:38

I\'m having some issues implementing a TimePicker in my application that allows the user to change the time of a database record prior to inserting it.

The problem is th

11条回答
  •  深忆病人
    2021-02-05 13:20

    Had the same issue when creating the TimePicker in code and none of the provided solutions worked for me. Below was what I ended up doing. Tested on API levels 18, 21 and 23

    final TimePicker tp = new TimePicker(getContext());
    tp.setOnTimeChangedListener(this);
    try {
        ViewGroup amPmView;
        ViewGroup v1 = (ViewGroup)tp.getChildAt(0);
        ViewGroup v2 = (ViewGroup)v1.getChildAt(0);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            ViewGroup v3 = (ViewGroup)v2.getChildAt(0);
            amPmView = (ViewGroup)v3.getChildAt(3);
        } else {
            amPmView = (ViewGroup)v2.getChildAt(3);
        }
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tp.setCurrentHour((tp.getCurrentHour() + 12) % 24);
            }
        };
        View am = amPmView.getChildAt(0);
        View pm = amPmView.getChildAt(1);
        am.setOnClickListener(listener);
        pm.setOnClickListener(listener);
    } catch (Exception e) {
        // DO nothing... just ignore the workaround if this fails.
    }
    

提交回复
热议问题