2016-11-14 68 views
0

我想只用一个onTouchListener()为多个按钮,这是我有的代码,但它不工作。 我想要做的是当我按下按钮,如果有另一个按钮(右或左)来编写代码,如果它没有按另一个按钮来编写另一个代码。我对Java很新,所以可能会有很多错误。 如果你有我的问题的另一种解决方案,请帮助!只有一个方法来实现onTouchListener()多个按钮

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); 
+0

看来你只是''touchListener'设置'btnup',也许你需要为其他人设置它? – mojarras

回答

0

我已经注意到:

  • 在监听器类降abstract关键字(您不能创建抽象类的实例) 。
  • 你的外部开关看起来不错,但内部的(检测附加按钮被按下的开关)没有意义。
  • 确保您将侦听器设置为全部四个按钮。

v您在侦听器中收到的视图是被按下(或释放或取消)的视图。为了检测Y按钮是否同时按下按钮X,您需要使用来自MotionEvent对象的信息,该信息告诉您事件是按下还是释放,并且保持每个按钮的状态。你可以看到一个处理运动事件的简单例子here。另请查看MotionEvent上的Android documentation

0

使用void setTag (Object tag)documentation)来设置蓝牙命令代码这样每个按钮:

btnup.setTag("#1000#"); 
btndown.setTag("#2000#"); 
btnleft.setTag("#1002#"); 
btnright.setTag("#1001#"); 

,比OnTouch类似的东西:

public boolean OnTouch(View v,MotionEvent event) { 
    mBluetooth.write((String)v.getTag()) 
} 

附:似乎你有错误的嵌套switch陈述。你需要分析v.getId()event.getAction() == MotionEvent.ACTION_UP或类似的东西,而不是每次v.getId()

相关问题