我正在尝试查看是否有一种方法可以创建一个方法来实现多个按钮的触摸侦听器,因为我有很多按钮可以做几乎完全相同的事情。他们所做的唯一区别是他们将通过我的 sendMessage() 方法发送的消息,以及需要按住按钮多长时间才能发送消息。如果有办法做到这一点,那可能是什么?而且,为什么这样的东西不起作用?
//Within onCreate Method...
Button mButton = (Button) findViewbyId(R.id.three_sec_button);
mButton = addTouchTimer(mButton, 3, 3);
通话 -
private Button addTouchTimer(Button button, final int sec, final int messageNum){
button.setOnTouchListener(new View.OnTouchListener() {
boolean longEnough = false;
long realTimeLeft = sec * 1000;
@Override
// This will make it so that a message is only sent if the button is held down for 3 seconds
// Otherwise it won't send. It is sent during the hold down process, releasing it returns a false
// value and no message is sent.
public boolean onTouch(View arg0, MotionEvent arg1) {
Log.d("Button", "Touchy Touchy!");
if(arg1.getAction() == MotionEvent.ACTION_DOWN){
buttonPressTime = new CountDownTimer(realTimeLeft, 1000){
@Override
public void onTick(long millisUntilDone){
realTimeLeft = millisUntilDone;
}
@Override
public void onFinish() {
long timeLeft = realTimeLeft;
long currTime = System.currentTimeMillis();
long realFinishTime = currTime + timeLeft;
while(currTime < realFinishTime){
currTime = System.currentTimeMillis();
}
longEnough = true;
sendEmergencyMessage(longEnough, messageNum);
}
}.start();
}
else if(arg1.getAction() == MotionEvent.ACTION_UP){
buttonPressTime.cancel();
sendMessage(longEnough, messageNum);
}
return longEnough;
}
});
return button;
}
似乎为了提高效率,必须有比为每个按钮实现单独的侦听器更好的方法。需要注意的是, sendMessage() 在其中有一个使用布尔值的 Log 调用,我想看看它在传递时的设置。这是在释放按钮期间调用它的唯一原因。