【问题标题】:Is it possible to use OnClickListener and OnTouchListener at the same time for a button?按钮是否可以同时使用 OnClickListener 和 OnTouchListener?
【发布时间】:2019-11-16 07:39:51
【问题描述】:

可以同时使用 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;
    }
}

【问题讨论】:

  • 你是从onTouch()无条件返回true,表示事件已经处理,所以不会继续到OnClickListener。目前尚不清楚您要采取什么行为,但如果您希望 OnTouchListener 充当“被动观察者”,则改为 return false;
  • 不要同时实现这两者,因为用户onTouch 完全不会注意到它,只需实现 onClick 即可满足您的要求。 :) make 很简单,而不是乱七八糟 ;)

标签: android-studio onclicklistener ontouchlistener


【解决方案1】:
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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多