Dialog实例中EditText为null

时间:2018-07-29 09:35:10

标签: android android-layout nullpointerexception android-edittext butterknife

我有一个对话框,该对话框在首次运行时弹出,并提示用户在editText视图中输入其用户名,但是每当我尝试通过执行editText.getText();访问其文本时,我都会收到NullPointerException消息,指出editText为空。我在这里想念什么?我尝试扩大布局并从Activity中访问.getText()方法,但一无所获。这是我的代码:

public class UsernameDialog extends DialogFragment {

@BindView(R.id.editText) EditText mEditText;
@BindView(R.id.username)
TextView menu_usr;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // inflate the layout using the dialog themed context
    final Context context = getActivity();
    final LayoutInflater inflater = LayoutInflater.from(context);
    final View view = inflater.inflate(R.layout.username_dialog,null,false);

    DialogInterface.OnClickListener posListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            menu_usr.setText(mEditText.getText());
            Log.d("USERNAME",mEditText.getText().toString());
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
            .setTitle("Choose your username")
            .setView(view)
            .setPositiveButton("OK",posListener);
    return builder.create();
}
}

错误日志:

  Process: com.dcv.spdesigns.dokkancards, PID: 373
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
    at com.dcv.spdesigns.dokkancards.ui.UsernameDialog$1.onClick(UsernameDialog.java:48)
    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6938)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

1 个答案:

答案 0 :(得分:1)

添加

Butterknife.bind(this,view)