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
Velval solution is the only solution that works and compatiple with different Android vesrions. I tried it on api 17 and 23. but it has an issue that it prevent original on click listener on Android 6. so here is what worked with me. to use touch instead of click:
public class MyTimePicker extends TimePicker {
private OnTimeChangedListener onTimeChangedListener;
public MyTimePicker(Context context) {
super(context);
// init();
}
public MyTimePicker(Context context, AttributeSet attrs) {
super(context, attrs);
//init();
}
public MyTimePicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MyTimePicker(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// Stop ScrollView from getting involved once you interact with the View
if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {
ViewParent p = getParent();
if (p != null)
p.requestDisallowInterceptTouchEvent(true);
}
return false;
}
@Override
public void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener) {
super.setOnTimeChangedListener(onTimeChangedListener);
this.onTimeChangedListener = onTimeChangedListener;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
init();
}
private void init() {
try {
ViewGroup amPmView;
ViewGroup v1 = (ViewGroup) 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.OnTouchListener listener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
onTimeChangedListener.onTimeChanged(MyTimePicker.this, getCurrentHour(), getCurrentMinute());
} else {
int hour = getCurrentHour();
if (hour >= 12) {
hour -= 12;
} else {
hour += 12;
}
onTimeChangedListener.onTimeChanged(MyTimePicker.this, hour, getCurrentMinute());
}
return false;
}
};
View am = amPmView.getChildAt(0);
View pm = amPmView.getChildAt(1);
am.setOnTouchListener(listener);
pm.setOnTouchListener(listener);
} catch (Exception e) {
// DO nothing... just ignore the workaround if this fails.
}
}
}