我试图让对话框触发一个意图,然后关闭。
public class PinMessage extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Random random = new Random();
final int pin = random.nextInt(9000) +1000;
builder.setMessage( "Your pin is " + (pin)+". Please note in case of password loss.")
.setTitle("Security PIN")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SharedPreferences launch_track = PreferenceManager
.getDefaultSharedPreferences(MainActivity.context);
SharedPreferences.Editor editor1 = launch_track.edit();
editor1.putInt("pin", pin);
editor1.commit();
//This triggers before the dialog closes
Intent lock = new Intent(context,AppLockService.class);
context.startService(lock);
// FIRE ZE MISSILES!
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
单击“确定”按钮,除了触发意图和启动服务外,我还希望关闭对话框。
目前,当我按下OK时,意图被触发并且服务在后台启动,但对话框没有关闭,我必须按下电话按钮才能退出。请帮帮我。
答案 0 :(得分:3)
public void onClick(DialogInterface dialog, int id)
正如您所看到的,您可以访问方法中的对话框,只需调用dismiss:
dialog.dismiss();
答案 1 :(得分:1)
创建 AlertDialog
的引用AlertDialog alertDialog = builder.create();
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// Start the Service and your required code
alertDialog.dismiss();
}
});
return alertDialog;
或强>
您将通过 onClick
获得对话框参考@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// Start the Service and your required code
dialog.dismiss();
}
答案 2 :(得分:0)
你可以用这个
来做dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
//your implementation while on dismiss
}
});
同时在dialog.dismiss();
onClick