Search code examples
android-studioonclicklistenerontouchlistener

Is it possible to use OnClickListener and OnTouchListener at the same time for a button?


Is it possible to use OnClickListener and OnTouchListener at the same time? I would have possibilities to process both user's actions: OnClick and OnTouch for the same Button. Thank you in advance for any hint. In my case, onClickListener does not work.

import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = findViewById(R.id.button);

        View.OnClickListener onClickListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int stop=1;

            }
        };

        btn.setOnClickListener(onClickListener);
        btn.setOnTouchListener(this);
    }


    @Override
    public boolean onTouch(View view, MotionEvent event) {

        int stop=1;
        return true;
    }
}

Solution

  • It depends on your requirement.
    
    onTouch gives you Motion Event. Thus, you can do a lot of fancy things as it help you separate state of movement. Like:
    
    ACTION_UP
    ACTION_DOWN
    ACTION_MOVE
    
    On the other hand, onClick doesn't give you much except which view user interacts. onClick is a complete event comprising of focusing,pressing and releasing. So, you have little control over it. One side up is it is very simple to implement.
    
    So, It is not necessary unless you want to mess up with your user. If you just want simple click event, go for onClick. If you want more than click, go for onTouch. Doing both will complicate the process.