Android按键操作——可识别按键动作(按下、松开、点击)
参考文章:http://blog.chinaunix.net/uid-26993600-id-3304530.html
下面介绍一下操作步骤:
1、编写buttonListener类
class buttonListener implements OnClickListener, OnTouchListener {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.forward)
{
if(arg1.getAction() == MotionEvent.ACTION_DOWN)
{
sendMessage("1");
}
if(arg1.getAction() == MotionEvent.ACTION_UP)
{
sendMessage("0");
}
}
return false;
}
}
2、获取按钮并为其设置监听器
//get the buttons
private Button mForwardButton;
mForwardButton = (Button) findViewById(R.id.forward);
buttonListener blForward = new buttonListener();
//set touch listener for the buttons
mForwardButton.setOnTouchListener(blForward);
//set click listener for the buttons
mForwardButton.setOnClickListener(blForward);
3、编写按键触发相应动作时的执行代码
其实就在buttonListener类中的onTouch()和onClick()函数中。