我试图构建一个简单的对话框片段,其中包含一个textview和两个按钮(send和cancel)。
当textview第一次为空时,我想禁用该按钮,但我的代码中的positiveButton变量始终为空,我得到以下异常:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
这是代码:
public class SendFriendRequestFragment extends DialogFragment {
private TextView tvEmail = null;
Button positiveButton = null;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View layout = inflater.inflate(R.layout.fragment_send_friend_request, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setTitle("Send request")
.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String email = tvEmail.getText().toString().trim();
if (validateInput()) {
SendFriendRequest(getActivity(), email);
} else {
Toast.makeText(getActivity(), "Request cannot be sent", Toast.LENGTH_LONG).show();
return;
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
Dialog dialog = builder.create();
positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false); // positiveButton is null and this call raises an exception !
tvEmail = (TextView) layout.findViewById(R.id.email);
tvEmail.addTextChangedListener(new InputTextWatcher(tvEmail));
// Create the AlertDialog object and return it
//return builder.create();
return dialog;
}
// Other functions that use the two variables positiveButton and tvEmail ...
}
有谁能告诉我如何解决我的问题,什么是最好的方法,以获得一个指针的按钮和视图包含在使用的布局?
谢谢您!
最佳答案
在显示Button
之前,实际上不会创建阳性的Dialog
。因为您在DialogFragment
中,所以您不能直接处理show()
上的Dialog
调用。您可以在OnShowListener
上设置AlertDialog
,但是在Button
的DialogFragment
方法中获得onStart()
可能更简单。
@Override
public void onStart() {
super.onStart();
positiveButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
...
}