2

我正在尝试在 DialogFragment 上设置侦听器,但不断收到空指针异常。

这是我的 DialogFragment 子类:

public static class TermsFragment extends DialogFragment {
        TextView t;
        private static String terms;

        static TermsFragment newInstance(String termsCond) {
            TermsFragment f = new TermsFragment();
            terms = termsCond;
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            getDialog().setCanceledOnTouchOutside(true);
            View v = inflater.inflate(R.layout.termsandconditions, container, false);

            getDialog().setTitle("Terms and Conditions");

            t = (TextView) v.findViewById(R.id.termsText);

            t.setText(terms);

            return v;
        }
    }

我从我的主要 SherlockFragment 中调用它,如下所示:

TermsFragment newFragment = TermsFragment.newInstance(terms);
newFragment.show(getFragmentManager(), "dialog");

这显示我的对话框很好。当我尝试添加这样的按钮侦听器时:

TermsFragment newFragment = TermsFragment.newInstance(terms);
Button cancel = (Button) newFragment.getDialog().findViewById(R.id.btnCancel);
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "Clicked");

            }
        });

或像这样的一般 onCancel 侦听器:

newFragment.getDialog().setOnCancelListener(new Dialog.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                showLoadingView(false);

            }
        });

在显示对话框之前,我的应用程序因空指针异常而崩溃。

我究竟做错了什么?

4

1 回答 1

1

而不是使用public View onCreateView你为什么不尝试使用public Dialog onCreateDialog. 这是一个例子:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    Bundle args = getArguments();
    currentName = args.getString(ARG_CURRENT_NAME);

    builder.setView(inflater.inflate(R.layout.name_dialog, null));
    builder.setTitle("Rename Rapper Program");
    builder.setMessage("Enter a new name for " + currentName + ":"); 
    builder.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            newName = (EditText) getDialog().findViewById(R.id.new_name);
            newProgName = newName.getText().toString();
            mRename.renameProgram(currentName, newProgName);
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dismiss();
        }
    });

    return builder.create();    
}

你将继续使用.show()你现在拥有的,你可以在你想要达到的目标之后对其进行建模。

于 2013-04-24T12:36:33.757 回答