英文:
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().
专注分享java语言的经验与见解,让所有开发者获益!
评论