`onTouchEvent`和`onClickListener`不能在同一个页面上一起使用。

huangapple 未分类评论51阅读模式
英文:

onTouchEvent and onClickListener can't work together on the same page

问题

例如,如果我有一些带有onclick监听器的按钮,并且屏幕的其余部分接收ontouch事件。ontouch事件会干扰onclick事件,除非你抬起ontouch手指,否则onclick不会响应。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        mAttackButton = findViewById(R.id.attack);
        mJumpButton = findViewById(R.id.jump);
        mAttackButton.setOnClickListener(this);
        mJumpButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.attack:
                attack();
                break;
            case R.id.jump:
                jump();
                break;
        }
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        mTouchPoint.x = event.getX();
        mTouchPoint.y = event.getY();
        return true;
    }
}
英文:

For example, if I have some buttons with onclick listener and the rest of the screen recieves ontouch event.The ontouch event will jam the onclick event unless you lift up the ontouch finger the onclick will not respond.

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);        
    mAttackButton        = findViewById(R.id.attack);
    mJumpButton          = findViewById(R.id.jump);
    mAttackButton.setOnClickListener(this);
    mJumpButton  .setOnClickListener(this);}

   @Override
   public void onClick(View view) {
    switch (view.getId()) {
        case R.id.attack:
        attack();
        break;
        case R.id.jump;
        jump();
        break;
     }
   }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
     super.onTouchEvent(event);
     mTouchPoint.x=event.getX();
     mTouchPoint.y=event.getY();
     return true;
 }
}

答案1

得分: 0

你可以随时拆分 onClickListener()。不必将整个活动全部实现。尝试将 onClickListener() 单独添加到每个视图上。OnTouchEvent() 也是同样的情况。

英文:

You can always split the onClickListener(). Instead of implementing the entirety of the activity. Try adding onClickListener() to each view individually. Same with the OnTouchEvent().

huangapple
  • 本文由 发表于 2020年6月29日 16:17:23
  • 转载请务必保留本文链接:https://java.coder-hub.com/62633885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定