如何不活动的某些秒后关闭对话框? [英] How to close a Dialog after certain seconds of inactivity?
问题描述
我有一个包含一个对话框,应用程序
i have an app that contains a dialog
我想X秒后关闭此对话框,当用户还没有任何与应用进行互动,如音量搜索栏弹出(这是当打开音量键点击,并闲置后2秒关闭)。
什么是实现这个最简单的方法是什么?
i want to close this dialog after x second, when user haven't any interact with app, like volume seekbar popup(that's open when the volume button clicked, and closed after 2 second of inactivity). what is the simplest way to implement this?
感谢您
推荐答案
例如,你可以使用一个处理程序并调用其.removeCallbacks()和.postDelayed()方法,每次用户与对话框交互。
You could for example use a Handler and call its .removeCallbacks() and .postDelayed() method everytime the user interacts with the dialog.
当一个互动,.removeCallbacks()方法将取消.postDelayed()的执行,并紧接着,U启动一个新的Runnable与.postDelayed()
Upon an interaction, the .removeCallbacks() method will cancel the execution of .postDelayed(), and right after that, u start a new Runnable with .postDelayed()
这里面运行的,你可以关闭对话框。
Inside this Runnable, you could close the dialog.
// a dialog
final Dialog dialog = new Dialog(getApplicationContext());
// the code inside run() will be executed if .postDelayed() reaches its delay time
final Runnable runnable = new Runnable() {
@Override
public void run() {
dialog.dismiss(); // hide dialog
}
};
Button interaction = (Button) findViewById(R.id.bottom);
final Handler h = new Handler();
// pressing the button is an "interaction" for example
interaction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
h.removeCallbacks(runnable); // cancel the running action (the hiding process)
h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds
}
});
有关跟踪用户的交互,可以使用:
For tracking user interaction, you could use:
@Override
public void onUserInteraction(){
h.removeCallbacks(runnable); // cancel the running action (the hiding process)
h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds
}
其中在您的活动是可用的。
Which is available in your activity.
这篇关于如何不活动的某些秒后关闭对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!