gpt4 book ai didi

android - 如何在长按按钮时发送字符流

转载 作者:行者123 更新时间:2023-11-29 19:47:48 26 4
gpt4 key购买 nike

如何在长按按钮时发送字符流。这是按钮长按的代码,

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
}
});

我想通过长按按钮发送字符流,直到用户松开按钮。

最佳答案

像这样尝试制作自定义 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);
}
}));

关于android - 如何在长按按钮时发送字符流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37429844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com