片段应该是静态的,以便可以由系统重新实例化,并且匿名类不是静态的 [英] Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static

查看:94
本文介绍了片段应该是静态的,以便可以由系统重新实例化,并且匿名类不是静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码显示了以下错误:

The following code shows me the following error:

片段应该是静态的,以便可以由系统重新实例化,并且匿名类不是静态的"

"Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static"

我该如何解决?

public void A(){
    final DialogFragment dialogFragment =
        new DialogFragment() {

        @Override
        public Dialog onCreateDialog(Bundle bundle) {
            AlertDialog.Builder builder =
                new AlertDialog.Builder(getActivity());

            builder.setMessage("Hello");
            builder.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        B();
                    }
                }
            );

            return builder.create();
        }
    };
}

private void B() {
    //...
}

推荐答案

读取片段生命周期您应该这样使用

Read fragment life cycle You should use like this

public static 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;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int title = getArguments().getInt("title");

        return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setPositiveButton(R.string.alert_dialog_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doPositiveClick();
                        }
                    }
                )
                .setNegativeButton(R.string.alert_dialog_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doNegativeClick();
                        }
                    }
                )
                .create();
    }
}

这篇关于片段应该是静态的,以便可以由系统重新实例化,并且匿名类不是静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆