如何长按按钮发送字符流。 这是按钮LongClick上的代码,
btnDown.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
sendMessage("S");//Here I wanted to send for example SSSSS on long press of that button
}
});
我想长按一个按钮发送一串字符,直到用户释放按钮。
答案 0 :(得分:2)
尝试这样做自定义Listner
String mString="";
public class ContinousRepeatListener implements View.OnTouchListener {
private Handler handler = new Handler();
private int initialInterval;
private final int normalInterval;
private final View.OnClickListener clickListener;
private Runnable handlerRunnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, normalInterval);
clickListener.onClick(downView);
}
};
private View downView;
/**
* @param initialInterval The interval after first click event
* @param normalInterval The interval after second and subsequent click
* events
* @param clickListener The OnClickListener, that will be called
* periodically
*/
public ContinousRepeatListener (int initialInterval, int normalInterval,
View.OnClickListener clickListener) {
if (clickListener == null)
throw new IllegalArgumentException("null runnable");
if (initialInterval < 0 || normalInterval < 0)
throw new IllegalArgumentException("negative interval");
this.initialInterval = initialInterval;
this.normalInterval = normalInterval;
this.clickListener = clickListener;
}
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
downView = view;
downView.setPressed(true);
clickListener.onClick(view);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handler.removeCallbacks(handlerRunnable);
downView.setPressed(false);
downView = null;
return true;
}
return false;
}
}
并像这样使用
btnDown.setOnTouchListener(new ContinousRepeatListener(400, 100, new View.OnClickListener() {
@Override
public void onClick(View view) {
// the code to execute repeatedly
mString += "S";
tvString.setText(mString);
}
}));
答案 1 :(得分:0)
使用setOnTouchListener并在ACTION_DOWN上编写sendMessage代码