Ответ 1
В следующем примере показано, как установить повторяющуюся задачу на пользовательском представлении. Задача работает с помощью обработчика, который запускает некоторый код каждую секунду. Прикосновение к виду начинается и останавливается.
public class MyCustomView extends View {
private static final int DELAY = 1000; // 1 second
private Handler mHandler;
// keep track of the current color and whether the task is running
private boolean isBlue = true;
private boolean isRunning = false;
// constructors
public MyCustomView(Context context) {
this(context, null, 0);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mHandler = new Handler();
}
// start or stop the blinking when the view is touched
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isRunning) {
stopRepeatingTask();
} else {
startRepeatingTask();
}
isRunning = !isRunning;
}
return true;
}
// alternate the view background color
Runnable mRunnableCode = new Runnable() {
@Override
public void run() {
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 task
void startRepeatingTask() {
mRunnableCode.run();
}
// stop running the task, cancel any current code that is waiting to run
void stopRepeatingTask() {
mHandler.removeCallbacks(mRunnableCode);
}
// make sure that the handler cancels any tasks left when the view is destroyed
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stopRepeatingTask();
}
}
Вот как выглядит изображение после нажатия.
Благодаря этому ответу для идей.