点击Dismiss DialogFragment

10

我想制作一个DialogFragment,当点击时可以关闭它,经过一些搜索,我决定采用以下实现方法:

public class ErrorDialogFragment extends RoboDialogFragment {

private static final String MESSAGE_ARG = "message";
private TextView text;

public ErrorDialogFragment newInstance (String message){
    ErrorDialogFragment f = new ErrorDialogFragment();

        Bundle args = new Bundle();
        args.putString(MESSAGE_ARG, message);
        f.setArguments(args);

        return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
    View v = inflater.inflate(R.layout.error_dialog_fragment, container, false);
    v.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ErrorDialogFragment.this.dismiss();
        }
    });

    text = (TextView) v.findViewById(R.id.error_dialog_text_textView);
    text.setText(getArguments().getString(MESSAGE_ARG));
    return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, 0);
}

弹出对话框可以有自定义消息,并在被点击后消失。

你认为还有更好的方法来实现这个吗?

谢谢。

3个回答

14

谢谢@Raghav,我现在正在使用setCanceledOnTouchOutside,但是对于内部点击,我将继续使用我的方法,该链接指的是一个Activity而不是DialogFragment :) - Goofyahead
你可以告诉我在哪里调用setCanceledOnTouchOutside方法吗?因为我需要对话框对象。 - Sandra
请将以下与编程有关的内容从英语翻译为中文。仅返回翻译后的文本:只需将其写在您执行对话的所有其他操作中。 - Rookie

1
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(msg);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which) 
            {
                alertDialog.dismiss();
            }
        });
        alertDialog.setIcon(R.drawable.error_icon);
        alertDialog.show();

每当您想显示警报时,只需使用此代码即可。在单击事件中,对话框将被关闭。


谢谢@user1208720,但我的类继承自DialogFragment(有意不是AlertDialog),并且它不会在单击按钮时关闭,而是在视图上的任何位置单击时关闭。 问题是关于如何从Android框架中使用这个DialogFragment类,并正确地分派此类事件的 :) - Goofyahead

1
我是从Activity中调用了一个DialogFragment。在对话框中点击按钮后,我使用接口来调用活动中的一个方法。在该活动中,我执行以下操作:
// This is the code inside the activity that call the dialog
Fragment fragment = getSupportFragmentManager().findFragmentByTag("MyDialog");
if(fragment != null) {
    DialogFragment dialog = (DialogFragment) fragment;
    dialog.dismiss();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接