设置Dialog点击背景屏幕 Dialog不消失

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:38   1174   0

最重要的一句是

dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失


业务的需求是变化莫测的,最近就遇到一个需求是——用户只有点击Dialog的取消按钮才会消失,点击屏幕的时候不消失。Android ICS对UI做了很大的变动,系统提倡使用DialogFragment,但是系统默认的操作习惯是点击屏幕Dialog会自动消失。

为了实现业务的需求,想过使用Dialog风格的Activity,但是做出来的效果和系统的UI效果不匹配,最终只有失败告终。在黔驴技穷的时候,决定再仔细撸一下Android文档,终于在文档中发现了Dialog的setCanceledOnTouchOutside属性,具体使用如下:

  1. public class MyAlertDialogFragment extends DialogFragment {
  2. public static MyAlertDialogFragment newInstance(int title) {
  3. MyAlertDialogFragment frag = new MyAlertDialogFragment();
  4. Bundle args = new Bundle();
  5. args.putInt("title", title);
  6. frag.setArguments(args);
  7. return frag;
  8. }
  9. @TargetApi(11)
  10. @Override
  11. public Dialog onCreateDialog(Bundle savedInstanceState) {
  12. int title = getArguments().getInt("title");
  13. AlertDialog dialog = new AlertDialog.Builder(getActivity())
  14. .setIcon(R.drawable.ic_launcher)
  15. .setTitle(title)
  16. .setPositiveButton(R.string.alert_dialog_ok,
  17. new DialogInterface.OnClickListener() {
  18. public void onClick(DialogInterface dialog, int whichButton) {
  19. ((MainActivity)getActivity()).doPositiveClick();
  20. }
  21. }
  22. )
  23. .setNegativeButton(R.string.alert_dialog_cancel,
  24. new DialogInterface.OnClickListener() {
  25. public void onClick(DialogInterface dialog, int whichButton) {
  26. ((MainActivity)getActivity()).doNegativeClick();
  27. }
  28. }
  29. )
  30. .create();
  31. dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
  32. return dialog;
  33. }
  34. }

以上只是设置Dialog的一个小技巧,希望对大家有所帮助。


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP