歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 4.0設置Dialog點擊屏幕不消失

Android 4.0設置Dialog點擊屏幕不消失

日期:2017/3/1 10:09:08   编辑:Linux編程

業務的需求是變化莫測的,最近就遇到一個需求是——用戶只有點擊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的一個小技巧,希望對大家有所幫助。

Copyright © Linux教程網 All Rights Reserved