EditText inside AlertDialog always null

前端 未结 3 1228
孤城傲影
孤城傲影 2020-12-07 04:07

I\'ve search over the threads but so far I have not found what I\'m looking for. I created a custom Alert Dialog that show up and I can do almost anything with it. It custom

相关标签:
3条回答
  • 2020-12-07 04:21

    Take note of how all of your method calls are being resolved within your anonymous inner classes.

    findViewById is a method that exists on views and on your activity. The version of this method on your activity searches for a view within the activity window's view hierarchy. The version on views searches that view instance and all attached children.

    Your call on the problematic line of code:

    EditText txtAccName = (EditText) findViewById(R.id.txtEditName);
    

    is resolving to Activity#findViewById. But your dialog's layout is not attached to your activity window, it's attached to the dialog. You can find the correct view reference in several ways but the simplest in your case is probably to search from the root of the layout that you inflated:

    EditText txtAccName = (EditText) layout.findViewById(R.id.txtEditName);
    
    0 讨论(0)
  • 2020-12-07 04:32

    When you use findViewById you implicitly refer to the current activity. The part you have to change is

    EditText txtAccName = (EditText) ad.findViewById(R.id.txtEditName);
    

    instead of

    EditText txtAccName = (EditText) findViewById(R.id.txtEditName);
    

    when you attempt to resolve it. You'll also have to change the scope of the AlertDialog object ad to class-wide and make sure that it's not null, before you search for views in it. That's pretty much it.

    0 讨论(0)
  • 2020-12-07 04:40

    The explanation by adamp is great. But that method didn't work for me. The simplest way for me is like this:

    builder.setPositiveButton(R.string.positive, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       Dialog dialogView = (Dialog) dialog;
                       EditText et;
                       et = (EditText) dialogView.findViewById(R.id.addressinput);
    

    Hope this helps somebody.

    0 讨论(0)
提交回复
热议问题