与标题一样,如何从自定义对话框中的EditText中获取文本?
这是我的dialogfragment中的onCreateDialog方法:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPref.edit();
builder.setView(inflater.inflate(R.layout.name_dialog, null))
.setPositiveButton(R.string.name_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
editor.putString(getString(R.string.name_key), nameEditText.getText().toString());
editor.commit();
}
})
.setNegativeButton(R.string.name_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
NameDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
我无法让它工作..我在edittext中写了一些东西然后我按OK它只是崩溃并在这一行给我一个空指针错误:
editor.putString(getString(R.string.name_key), nameEditText.getText().toString());
答案 0 :(得分:3)
您正在错误的View中查找EditText。它不是Activity的一部分,它是对话框的一部分。因此,请检查视图的对话框:
Dialog dialogView = dialog.getDialog();
EditText paymentEt = (EditText) dialogView.findViewById(R.id.edittext_payment);
答案 1 :(得分:0)
而不是使用
EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
尝试使用此
Dialog dialg = (Dialog) dialog;
EditText et = (EditText) dialg.findViewById(R.id.search_input_text);
val = et.getText().toString();