Android Alert Dialog unable to find view

前端 未结 4 1604
花落未央
花落未央 2020-12-07 01:55

I\'m having trouble getting an AlertDialog to pass text back to the activity that calls it. It seems the issue is that it fails to find the proper EditText when calling fin

相关标签:
4条回答
  • 2020-12-07 02:02

    Your inflating a layout and you have this builder.setView(modifyView);

    So to initialize edittext replace

     final EditText editText = (EditText)getActivity().findViewById(R.id.modificationText);
    

    by

     final EditText editText = (EditText) modifyViewfindViewById(R.id.modificationText);
    

    findViewById looks for a view with id provided in the current inflated layout. You don't need getActivity instead use theinflated view object to initialize your EditText.

    public final Activity getActivity ()
    
    Added in API level 11
    Return the Activity this fragment is currently associated with.
    
    0 讨论(0)
  • 2020-12-07 02:04

    Change

    final EditText editText = (EditText) getActivity().findViewById(R.id.modificationText);
    

    to

    final EditText editText = (EditText) modifyView.findViewById(R.id.modificationText);
    

    Your EditText lives in modify_dialog.xml so you need to use the variable that was inflated with that layout (here modifyView) to find the id not the layout that getActivty() will look in.

    0 讨论(0)
  • 2020-12-07 02:14

    That's because you are searching the view from the activity try using modifyView.findView…

    0 讨论(0)
  • 2020-12-07 02:18

    Just this

    EditText editText = (EditText) modifyView.findViewById(R.id.modificationText);
    

    What was the problem?

    In activity you just findViewById any view you want which refers to activity layout. But in dialog, dialogFragments, or custom views you have to refer the current layout manually, like

    view.findViewById(...)
    

    As your code was referring to its parent activity so app tried to find the id in activity but actually your id belongs to your custom view modifyView.

    So this is correct way for your code to find that id.

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