我想创建一个按钮,按下时会发送'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();
}
}
答案 0 :(得分: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
}
};
答案 1 :(得分:4)
button.onKeyDown()=按下时执行某些操作 and 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();
}