2

我想创建一个按钮,按下时发送“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();
             }
          }
4

2 回答 2

6

利用:

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
    }
};
于 2013-08-20T20:15:10.883 回答
4

button.onKeyDown() = 按下时做某事 button.onKeyUp() = 释放时做某事或 button.onTouch() = 按下时做某事 button.onClick() = 释放时做某事

    btn2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
        makethisToastup();}});
    btn2.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View view, MotionEvent event) {
        makethisToastdown();
        return false;
    }});

public void makethisToastup(){
Toast.makeText(this, "Buttonup", Toast.LENGTH_LONG).show();
}
public void makethisToastdown(){
Toast.makeText(this, "Buttondown", Toast.LENGTH_LONG).show();
}
于 2012-05-04T15:19:03.437 回答