我有一个包含对话框的应用程序
我希望在x秒之后关闭此对话框,此时用户没有与应用程序进行任何交互,例如音量搜索栏弹出窗口(单击音量按钮时打开,并且在2秒钟不活动后关闭).
实现这个的最简单方法是什么?
谢谢
解决方法
例如,每次用户与对话框交互时,您都可以使用Handler并调用其.removeCallbacks()和.postDelayed()方法.
在进行交互时,.removeCallbacks()方法将取消.postDelayed()的执行,之后,你将使用.postDelayed()启动一个新的Runnable
在此Runnable中,您可以关闭对话框.
// 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 } });
要跟踪用户互动,您可以使用:
@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 }
您的活动中有哪些内容.