- #1
Darkmisc
- 213
- 28
- TL;DR Summary
- I want to create a counter that increments while a button is held down, but it crashes when I click on it. Is it because I don't have a delay after each increment?
Hi everyone
I modified some code that originally displayed a toast when the screen was pressed and held. The original code used onTouchListener with a relative layout, but I changed it to a button instead. I think I've copied it correctly, but my program crashes when the button is clicked.
I figured I needed a delay after n++, but adding one doesn't seem to help.
Which part of my code have I messed up? Android Studio doesn't highlight any errors and the code is able to compile.
Thanks
I modified some code that originally displayed a toast when the screen was pressed and held. The original code used onTouchListener with a relative layout, but I changed it to a button instead. I think I've copied it correctly, but my program crashes when the button is clicked.
I figured I needed a delay after n++, but adding one doesn't seem to help.
Which part of my code have I messed up? Android Studio doesn't highlight any errors and the code is able to compile.
Thanks
Android Studio java:
package com.example.clickcounter;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int n = 0;
Button button;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
TextView myText = (TextView) findViewById(R.id.textView);
Runnable mRunnable = new Runnable(){
public void run(){
n++;
myText.setText(n);
}
};
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
mHandler.postDelayed(mRunnable, 100);
}
return true;
}
});
}
}
Last edited by a moderator: