是否可以同时为一个按钮使用OnClickListener和OnTouchListener?

问题描述 投票:0回答:1

是否可以同时使用OnClickListener和OnTouchListener?我将有可能处理两个用户的操作:同一按钮的OnClick和OnTouch。预先感谢您的任何提示。就我而言,onClickListener不起作用。

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;
    }
}
android-studio onclicklistener ontouchlistener
1个回答
0
投票
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.
© www.soinside.com 2019 - 2024. All rights reserved.