Android 4.0设置Dialog点击屏幕不消失
业务的需求是变化莫测的,最近就遇到一个需求是——用户只有点击Dialog的取消按钮才会消失,点击屏幕的时候不消失。Android ICS对UI做了很大的变动,系统提倡使用DialogFragment,但是系统默认的操作习惯是点击屏幕Dialog会自动消失。
为了实现业务的需求,想过使用Dialog风格的Activity,但是做出来的效果和系统的UI效果不匹配,最终只有失败告终。在黔驴技穷的时候,决定再仔细撸一下Android文档,终于在文档中发现了Dialog的setCanceledOnTouchOutside属性,具体使用如下:
- public class MyAlertDialogFragment extends DialogFragment {
-
- public static MyAlertDialogFragment newInstance(int title) {
- MyAlertDialogFragment frag = new MyAlertDialogFragment();
- Bundle args = new Bundle();
- args.putInt("title", title);
- frag.setArguments(args);
- return frag;
- }
-
- @TargetApi(11)
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- int title = getArguments().getInt("title");
-
-
- AlertDialog dialog = new AlertDialog.Builder(getActivity())
- .setIcon(R.drawable.ic_launcher)
-
- .setTitle(title)
- .setPositiveButton(R.string.alert_dialog_ok,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- ((MainActivity)getActivity()).doPositiveClick();
- }
- }
- )
- .setNegativeButton(R.string.alert_dialog_cancel,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- ((MainActivity)getActivity()).doNegativeClick();
- }
- }
- )
- .create();
- dialog.setCanceledOnTouchOutside(false);
-
- return dialog;
- }
- }
以上只是设置Dialog的一个小技巧,希望对大家有所帮助。
|