Marshall
Marshall

Reputation: 1362

Ontouch functionality

I am making an app where when you hold a button, a textview with numbers increases (until you let go).

I tried using the OnTouch, but that doesn't increase the number unless you move your finger in the button. I tried looking at some answered questions here in stackoverflow and implementing the solutions suggested, but it seems to just crash now...

The ontouch listener:

upb.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            /* Button pressed */
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                startIncreasing();
            }
            if(event.getAction() == MotionEvent.ACTION_UP){
                stopIncreasing();
            }
            return true;
        }

        private void startIncreasing(){
            setIsIncreasing(true);
            new Thread(new Runnable() {
                public void run() {
                    while(isIncreasing()){
                        if(speed<12){ //max speed determined here
                            speed++;
                            speedtext.setText(speed + " km/h");
                            downb.setEnabled(true);
                            homeb.setEnabled(false);
                            revb.setEnabled(false);
                            //send signal to speed up
                         }
                        else {
                            speedtext.setText("MAX " + speed + " km/h");
                            upb.setEnabled(false);
                        }
                    }
                }
            }).start();
        }
}); 

Later on in the code:

synchronized private void stopIncreasing(){
        setIsIncreasing(false);
    }

    synchronized private boolean isIncreasing(){
        return continueIncreasing;
    }

    synchronized void setIsIncreasing(boolean newSetting){
        continueIncreasing = newSetting;
    }

Anybody that can spot what I am doing wrong? Or should I do this in a completely different way?

Thank you for your help

Upvotes: 0

Views: 73

Answers (1)

Daniel L.
Daniel L.

Reputation: 5140

Without seeing logs, I believe your app crashes since you're updating the TextView from a background thread (in speedtext.setText(speed + " km/h");). Updating UI elements must be done from the UI thread (main). You can use the runOnUiThread() method for doing such updates from the UI thread.

Upvotes: 1

Related Questions