我想创建一个按钮,按下时发送“w”,释放时发送“x”。按照我现在的编码方式,当我按下按钮时,它什么也不做,当我释放它时,它会发送“w”。我做错什么了?代码:

    but = new Button(this);
    but.setText("FORWARD");
    but.setGravity(Gravity.CENTER);
    but.setId(Tab2_Forward);
    but.setOnClickListener(this);
    but.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT));
    panelH.addView(but);

    public void onClick(View v) {
       int cmdId = v.getId();
       if (cmdId == Menu_Tab1) {
          startDiscoverBluetoothDevices();
       }
       if (cmdId == Tab2_Forward) {
          if (Bee_btSocket != null)
             try {
                 Bee_btSocket.getOutputStream().write('w');
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
          }

最佳答案

用途:

but.setOnTouchListener(btnTouch);


private View.OnTouchListener btnTouch = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN)
            System.out.println("Touch");
        else if (action == MotionEvent.ACTION_UP)
            System.out.println("Release");
        return false;   //  the listener has NOT consumed the event, pass it on
    }
};

10-08 18:20