我似乎无法绕开自定义对话框。我尝试了很多变化,但到目前为止没有运气。
这是我当前用于对话框的 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/Word"
android:text="Word?"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"/>
<EditText
android:layout_height="100dp"
android:layout_width="match_parent"
android:id="@+id/lookupWordEdit"
android:inputType="text"/>
</RelativeLayout>
这是代码:
public class LookupWordDialogFragment extends DialogFragment {
private EditText mEditText;
public LookupWordDialogFragment() {
// Empty constructor required for DialogFragment
}
public interface LookupWordDialogListener {
void onFinishEditDialog(String inputText);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final EditText lookupWordEdit = (EditText)getActivity().findViewById(R.id.lookupWordEdit);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_lookupword, null))
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// Return input text to activity
LayoutInflater inflater = getActivity().getLayoutInflater();
final EditText lookupWordEdit = (EditText)getActivity().findViewById(R.id.lookupWordEdit);
LookupWordDialogListener activity = (LookupWordDialogListener) getActivity();
activity.onFinishEditDialog(lookupWordEdit.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LookupWordDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
代码当前在此行上因空指针异常而崩溃:
activity.onFinishEditDialog(lookupWordEdit.getText().toString());
我怀疑我没有正确抓住lookupWordEdit。对话框非常简单。当用户点击 OK 按钮时,我应该如何获取输入的文本?
谢谢!