Repeat A Task With A Time Delay Inside A Custom View
The question Repeat a task with a time delay? talks about a repeated task within an activity. The top voted answer looks good for that situation. I am trying to make a blinking cur
Solution 1:
The following example shows how to set a repeating task on a custom view. The task works by using a handler that runs some code every second. Touching the view starts and stops the task.
publicclassMyCustomViewextendsView {
privatestaticfinalintDELAY=1000; // 1 secondprivate Handler mHandler;
// keep track of the current color and whether the task is runningprivatebooleanisBlue=true;
privatebooleanisRunning=false;
// constructorspublicMyCustomView(Context context) {
this(context, null, 0);
}
publicMyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
publicMyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
privatevoidinit() {
mHandler = newHandler();
}
// start or stop the blinking when the view is touched@OverridepublicbooleanonTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isRunning) {
stopRepeatingTask();
} else {
startRepeatingTask();
}
isRunning = !isRunning;
}
returntrue;
}
// alternate the view's background colorRunnablemRunnableCode=newRunnable() {
@Overridepublicvoidrun() {
if (isBlue) {
MyCustomView.this.setBackgroundColor(Color.RED);
}else {
MyCustomView.this.setBackgroundColor(Color.BLUE);
}
isBlue = !isBlue;
// repost the code to run again after a delay
mHandler.postDelayed(mRunnableCode, DELAY);
}
};
// start the taskvoidstartRepeatingTask() {
mRunnableCode.run();
}
// stop running the task, cancel any current code that is waiting to runvoidstopRepeatingTask() {
mHandler.removeCallbacks(mRunnableCode);
}
// make sure that the handler cancels any tasks left when the view is destroyed @OverrideprotectedvoidonDetachedFromWindow() {
super.onDetachedFromWindow();
stopRepeatingTask();
}
}
Here is what the view looks like after being clicked.
Thanks to this answer for ideas.
Post a Comment for "Repeat A Task With A Time Delay Inside A Custom View"