对话框在10秒后打开,不连续,我想在关闭后再等待10秒
如何制作
代码在这里
final Dialog dialog = new Dialog(this);
final Handler h = new Handler();
final int delay = 10000;
h.postDelayed(new Runnable() {
public void run() {
//do something
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
h.postDelayed(this, delay);
}
}, delay);
答案 0 :(得分:1)
在取消之前等待10秒
final Dialog dialog = new Dialog(this);
final Handler h = new Handler();
final int delay = 10000;
h.postDelayed(new Runnable() {
public void run() {
//do something
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
h.postDelayed(new Runnable() {
public void run() {
//this method will execute with a delay of after 10 seconds
dialog.dismiss();
}, delay);
}
});
dialog.show();
h.postDelayed(this, delay);
}
}, delay);
答案 1 :(得分:1)
首先为Handler声明一个全局变量,以便从Thread更新UI控件,如下所示
//time for 60 seconds
int time = 0;
Handler mHandler = new Handler();
public void showDialog(){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
@Override
public void run() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if(time<=60){
time += 10;
showDialog();
}
}
});
dialog.show();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
答案 2 :(得分:1)
我是这样做的,但应用程序已停止
public class MainActivity extends AppCompatActivity {
Handler mHandler = new Handler();
Dialog dialog = new Dialog(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showDialog(){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
@Override
public void run() {
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title...");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
showDialog();
}
});
dialog.show();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}