For the Android fans out there, here is the source:
package com.spleenware;
import java.util.TimerTask;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
/**
* Surprisingly, an AutoRepeatButton doesn't seem to be in the standard Android View frameworks.
* So, simple implementation here. When Button is held down its onClickListener is called on a timer.
*
* @author Scott Powell
*/
public class AutoRepeatButton extends Button
{
public AutoRepeatButton(Context c)
{
super(c);
}
/**
* Constructor used when inflating from layout XML
*/
public AutoRepeatButton(Context c, AttributeSet attrs)
{
super(c, attrs);
}
/**
* TODO: These could be made variable, and/or set from the XML (ie. AttributeSet)
*/
private static final int INITIAL_DELAY = 900;
private static final int REPEAT_INTERVAL = 100;
private TimerTask mTask = new TimerTask()
{
@Override
public void run()
{
if (isPressed())
{
performClick(); // simulate a 'click'
postDelayed(this, REPEAT_INTERVAL); // rinse and repeat...
}
}
};
@Override
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_DOWN)
postDelayed(mTask, INITIAL_DELAY);
else if (event.getAction() == MotionEvent.ACTION_UP)
removeCallbacks(mTask); // don't want the pending TimerTask to run now that Button is released!
return super.onTouchEvent(event);
}
}
Hey, worked like a charm. Many thanks! (I learned a lot from examining this code).
ReplyDeleteUsed it almost blindly, and worked great at first try... thanks!
ReplyDelete