I'm trying to create a button which when held would add 1 or any number to it until the button is released. My goal would be to create an on-screen cursor key controller to move around a button/bitmap. The below code only adds 1 when pressed down. How to get it to count it continuously?
Thanks for you help
package s.apps.kontroler;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity implements OnTouchListener {
Button up;
TextView text;
int countup;
boolean isDown = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
up = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.textView1);
up.setOnTouchListener(this);
}
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
int i = event.getAction();
if (i == MotionEvent.ACTION_DOWN) {
isDown = true;
if (isDown) {
countup++;
text.setText("Count is: " + countup);
}
else if (i == MotionEvent.ACTION_UP) {
isDown = false;
}
}
return true;
}
}
This should do it:
private static final int INTERVAL=500;
private Handler handler= new Handler();
private Runnable incrementRunnable = new Runnable() {
@Override
public void run() {
countup++;
text.setText("Count is: " + countup);
handler.postDelayed(this, INTERVAL);
}
}
public boolean onTouch(View arg0, MotionEvent event) {
int i = event.getAction();
if (i == MotionEvent.ACTION_DOWN) {
incrementRunnable.run();
}
else if (i == MotionEvent.ACTION_UP) {
handler.removeCallbacks(incrementRunnable);
}
return true;
}