重复一个动作,只要按下按钮
问题描述:
比方说,你有一个TextView
,显示一个数字为0,你有一个Button
。 现在,如果用户按下按钮,TextView中的数字将增加一个(我知道该怎么做),但如果用户按下按钮并且不释放它,那么TextView
中的数字应该增加,这应该只要用户不释放Button
就可以重复自我。 换句话说:只要用户按住按钮,如何一次又一次地增加数字?重复一个动作,只要按下按钮
答
一般的方法(不是特定于Android)将分别检测新闻和发布事件。新闻事件启动一个周期性任务(Runnable
或Thread
),它将添加到计数器(让我们说每秒5次,或每200毫秒一次)。发布事件会停止周期性任务。
答
- 建立一个
View.OnLongClickListener
你的按钮 - 给你的活动
Runnable
,并初始化(但不启动),当您加载活动 - 有OnLongClickListener做更新的定期异步任务文本框并检查自第一次点击以来的时间
- 创建一个
OnTouchListener
,当触摸事件被释放时暂停Runnable
。
我知道这是一个粗略的草稿,但是这是可以重复使用和修改一个非常有用的模式,所以它的价值下沉你的爪子把它...
答
你需要安排一个当您收到mousePressed
事件时发生异步重复事件,并在您收到mouseReleased
事件时停止它。
在Java中有很多方法可以处理这个问题。我喜欢使用java.util.concurrent
类,它们非常灵活。需要注意以下几点:
如果事件调度线程上没有发生异步事件,则需要使用SwingUtilities.invokeLater()
来设置JButton
文本。
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Frame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
final JButton button = new JButton("0");
final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
button.addMouseListener(new MouseAdapter()
{
int counter = 0;
ScheduledFuture<?> future;
@Override
public void mousePressed(MouseEvent e)
{
Runnable runnable = new Runnable()
{
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
button.setText(String.valueOf(counter++));
}
});
}
};
future = executor.scheduleAtFixedRate(runnable, 0, 200, TimeUnit.MILLISECONDS);
}
@Override
public void mouseReleased(MouseEvent e)
{
if (future != null)
{
future.cancel(true);
}
}
});
frame.add(button);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
+1这听起来像我描述更一般的Android特定过程。 – 2012-04-03 22:21:43