我正在尝试在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);
}
});
在显示对话框之前,我的应用程序因空指针异常而崩溃。
我做错了什么?
答案 0 :(得分: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()
,并且可以在您尝试实现之后对其进行建模。