aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/eu/siacs/conversations/ui/widget/Switch.java
blob: fd3b5553fe8d13998411eecaac0b8dbd118c63dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package eu.siacs.conversations.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import com.kyleduo.switchbutton.SwitchButton;

public class Switch extends SwitchButton {

	private int mTouchSlop;
	private int mClickTimeout;
	private float mStartX;
	private float mStartY;
	private OnClickListener mOnClickListener;

	public Switch(Context context) {
		super(context);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();
	}

	public Switch(Context context, AttributeSet attrs) {
		super(context, attrs);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();
	}

	public Switch(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
		mClickTimeout = ViewConfiguration.getPressedStateDuration() + ViewConfiguration.getTapTimeout();
	}

	@Override
	public void setOnClickListener(OnClickListener onClickListener) {
		this.mOnClickListener = onClickListener;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!isEnabled()) {
			float deltaX = event.getX() - mStartX;
			float deltaY = event.getY() - mStartY;
			int action = event.getAction();
			switch (action) {
				case MotionEvent.ACTION_DOWN:
					mStartX = event.getX();
					mStartY = event.getY();
					break;
				case MotionEvent.ACTION_CANCEL:
				case MotionEvent.ACTION_UP:
					float time = event.getEventTime() - event.getDownTime();
					if (deltaX < mTouchSlop && deltaY < mTouchSlop && time < mClickTimeout) {
						if (mOnClickListener != null) {
							this.mOnClickListener.onClick(this);
						}
					}
					break;
				default:
					break;
			}
			return true;
		}
		return super.onTouchEvent(event);
	}
}