Skip to content

Instantly share code, notes, and snippets.

@LouiS0616
Last active September 7, 2021 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LouiS0616/bd7157dba96c04a74af1d23fe11ef977 to your computer and use it in GitHub Desktop.
Save LouiS0616/bd7157dba96c04a74af1d23fe11ef977 to your computer and use it in GitHub Desktop.
Holdable button sample.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HoldableButton">
<attr name="delay_msec" format="integer" />
<attr name="interval_msec" format="integer" />
</declare-styleable>
</resources>
public class HoldableButton extends AppCompatButton {
private int delayMsec;
private int intervalMsec;
private MainTask mainTask;
private final Handler handler = new Handler();
private Runnable runnableCode;
//
//
public HoldableButton(Context context) {
this(context, null);
}
public HoldableButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HoldableButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(
context.obtainStyledAttributes(
attrs, R.styleable.HoldableButton, defStyleAttr, 0
)
);
setMainTask(() -> {});
}
private void initAttrs(TypedArray typedArray) {
delayMsec = typedArray.getInteger(
R.styleable.HoldableButton_delay_msec, 400
);
intervalMsec = typedArray.getInteger(
R.styleable.HoldableButton_interval_msec, 100
);
typedArray.recycle();
}
private void initListener() {
setOnClickListener(view -> mainTask.doTask());
//
runnableCode = () -> {
mainTask.doTask();
handler.postDelayed(runnableCode, intervalMsec);
};
setOnTouchListener(
(view, motionEvent) -> {
switch(motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(runnableCode, delayMsec);
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(runnableCode);
view.performClick();
break;
default:
break;
}
return true;
}
);
}
//
public void setMainTask(MainTask mainTask) {
this.mainTask = mainTask;
initListener();
}
//
//
@FunctionalInterface
public interface MainTask {
void doTask();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment