3 回答

TA貢獻1836條經(jīng)驗 獲得超5個贊
對于這樣的事情,我通常使用帶有Runnable 的處理程序,以便在 X用戶未執(zhí)行特定操作后執(zhí)行操作。milliseconds
首先,創(chuàng)建一個runnable
和一個handler
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
然后添加onClickListener:
myButton.setOnClickListener(new View.OnClickListener() {
? @Override
? public void onClick(View view) {? ? ? ??
? }
});
然后,在onClick事件內部,刪除callbacks并重新實例化,handler如下所示:
if(runnable != null) {
? // in this case the user already clicked once at least
? handler.removeCallbacks(runnable);
}
runnable = new Runnable() {
? @Override? ??
? public void run() {
? ? //this code will run when user isn't clicking for the time you set before.
? }
};
handler.postDelayed(runnable, DELAY);
最后結果:
final android.os.Handler handler = new android.os.Handler();
private Runnable runnable;
private final long DELAY = 3000; // how many milliseconds you want to wait
@Override
public void onCreate(Bundle savedInstanceState) {
? ? super.onCreate(savedInstanceState);
? ? // all your previous stuffs
? ? myButton.setOnClickListener(new View.OnClickListener() {
? ? ? @Override
? ? ? public void onClick(View view) {? ? ? ?
? ? ? ? if(runnable != null) {
? ? ? ? ? // in this case the user already clicked once at least
? ? ? ? ? handler.removeCallbacks(runnable);
? ? ? ? }
? ? ? ? runnable = new Runnable() {
? ? ? ? ? @Override? ??
? ? ? ? ? public void run() {
? ? ? ? ? ? //this code will run when user isn't clicking for the time you set before.
? ? ? ? ? }
? ? ? ? };
? ? ? ? handler.postDelayed(runnable, DELAY);?
? ? ? }
? ? });
}
我希望這會有所幫助,如有任何問題,請隨時提出

TA貢獻1850條經(jīng)驗 獲得超11個贊
Handler 可能會在這種場景下工作,有 3000 毫秒的延遲。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// do action
}
}, 3000);

TA貢獻1828條經(jīng)驗 獲得超6個贊
首先,您創(chuàng)建一個Timerwith a TimerTask(使用您的線程)并安排它在 3 秒后運行。
每次按下按鈕,您都會重置計時器。
public class MyClass{
private Timer timer=new Timer()
private TimerTask task=new TimerTask(){
public void run(){
//your action
}
};
public void init(){
timer.schedule(task,3000);
}
public void onButtonClick(){
task.cancel();
timer.schedule(task,3000);
}
}
添加回答
舉報