java只有一种方法可以将onTouchListener()实现为多个按钮
我试图对多个按钮使用一个onTouchListener(),这是我的代码,但它不起作用。 我想做的是当我按下按钮时,如果按下另一个按钮(右或左)来编写代码,如果没有按下另一个按钮来编写另一个代码。我对java非常陌生,所以可能会有很多错误。 如果你有另一个解决我问题的方法,请帮助我
abstract class MyTouchListener implements View.OnTouchListener{
public boolean OnTouch(View v,MotionEvent event){
switch (v.getId()){
case R.id.btnup:
switch (v.getId()){
case R.id.btnright:
mBluetooth.write("#1001#");
break;
case R.id.btnleft:
mBluetooth.write("#1002#");
break;
case R.id.btnup:
mBluetooth.write("#1000#");
break;
}
break;
case R.id.btnright:
mBluetooth.write("#0002#");
break;
case R.id.btnleft:
mBluetooth.write("#0001#");
break;
case R.id.btndown:
switch (v.getId()){
case R.id.btnright:
mBluetooth.write("#2001#");
break;
case R.id.btnleft:
mBluetooth.write("#2002#");
break;
case R.id.btndown:
mBluetooth.write("#2000#");
break;
}
}
return true; }
}}
以下是按钮:
btnup=(Button)findViewById(R.id.btnup);
btndown=(Button)findViewById(R.id.btndown);
btnleft=(Button)findViewById(R.id.btnleft);
btnright=(Button)findViewById(R.id.btnright);
MyTouchListener touchListener = new MyTouchListener();
btnup.setOnTouchListener(touchListener);
# 1 楼答案
我注意到:
abstract
关键字(不能创建抽象类的实例)李>您在侦听器中接收到的
v
视图是被按下(或释放,或取消)的视图。为了检测按钮Y同时按下时按钮X是否同时按下,您需要使用来自MotionEvent
对象的信息来告诉您事件是按下还是释放,并保持每个按钮的状态。您可以看到一个处理运动事件here的简单示例。还要检查MotionEvent上的Android documentation# 2 楼答案
使用
void setTag (Object tag)
(documentation)为每个按钮设置蓝牙命令代码,如下所示:而不是像这样的事情:
另外,您似乎有错误的嵌套
switch
语句。你需要分析v.getId()
和event.getAction() == MotionEvent.ACTION_UP
或者类似的东西,而不是每次都分析v.getId()