I'll admit straight off that I'm new to development and trying my hand at Android. I've been trying to search the 'net to find advice on how to implement some "Hold Button to Repeat Action" - I've created a custom numpad from buttons and want a backspace-like behaviour. Having got so far, I called upon a friend who hasn't coded Android before, but done lots of C# / Java and seems to know what he's doing.
The code below works just fine, but I feel it could be done more neatly. I apologise if I've missed bits out, but hopefully this explains my approach. I think the onTouchListener is ok, but the way Threads are handled doesn't feel right.
Is there a better or more simple way to do this?
public class MyApp extends Activity {
private boolean deleteThreadRunning = false;
private boolean cancelDeleteThread = false;
private Handler handler = new Handler();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//May have missed some declarations here...
Button_Del.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
handleDeleteDown();
return true;
}
case MotionEvent.ACTION_UP:
{
handleDeleteUp();
return true;
}
default:
return false;
}
}
private void handleDeleteDown() {
if (!deleteThreadRunning)
startDeleteThread();
}
private void startDeleteThread() {
Thread r = new Thread() {
@Override
public void run() {
try {
deleteThreadRunning = true;
while (!cancelDeleteThread) {
handler.post(new Runnable() {
@Override
public void run() {
deleteOneChar();
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(
"Could not wait between char delete.", e);
}
}
}
finally
{
deleteThreadRunning = false;
cancelDeleteThread = false;
}
}
};
// actually start the delete char thread
r.start();
}
});
}
private void handleDeleteUp() {
cancelDeleteThread = true;
}
private void deleteOneChar()
{
String result = getNumberInput().getText().toString();
int Length = result.length();
if (Length > 0)
getNumberInput().setText(result.substring(0, Length-1));
//I've not pasted getNumberInput(), but it gets the string I wish to delete chars from
}