Ivan Fazaniuk
Ivan Fazaniuk

Reputation: 1070

Discrete OnTouchListener events

Why does View.OnTouchListener() works so freaky when I just ask it to increment 1?

    public class Clicker extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.clicker);
        TextView t = (TextView) findViewById(R.id.counter);
        ImageView v = (ImageView) findViewById(R.id.image);
        if (v != null) {

            v.setOnTouchListener(new View.OnTouchListener() {
                int count = 3123;
                @Override
                public boolean onTouch(View arg0, MotionEvent me) {
                    v.setSelected(me.getAction()== MotionEvent.ACTION_DOWN);
                    count = count + 1;
                    t.setText(String.format("%d",count));
                    return true;
                }
            });
        }
    }
}

enter image description here 1 click increments 2 or 3 points.

Upvotes: 2

Views: 97

Answers (2)

Thomas
Thomas

Reputation: 1143

The onTouch method is called for many different touch events, including ACTION_DOWN, ACTION_MOVE, and ACTION_UP. Just by clicking the button, this method is called twice, once for the down press, and once when your finger is lifted. In order to count only once when the button is pressed, you would need to write something like this:

v.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN){
            count += 1;
        }
        return true;
    }
});

Upvotes: 1

elvisrusu
elvisrusu

Reputation: 378

The method:

onTouch(View arg0, MotionEvent me)

is called for every touch event. For a click you will receive two eventsMotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP also if you move the finger you can receive also a MotionEvent.ACTION_MOVE.

Upvotes: 1

Related Questions