1

I have a problem when trying to access my dialogs fragments view. Here is what I do:

For each button in my main activity I create a new dialogFragment when the button is clicked:

    button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment newFragment = ResAmountDialog.newInstance(R.string.res_dialog_title);
                newFragment.show(getFragmentManager(), "dialog");
                ImageView resIcon = (ImageView) newFragment.getView().findViewById(R.id.resourceIcon1);
                resIcon.setImageResource(currentResourceImage);
            }
    });

The dialog fragment consists of an EditText and ImageView. I'm trying to access the imageView in the above code by getting the fragment, then its view and then finding it by ID, but it returns null.

I tried to find a solution on the internet but all the similar problems had their views accessed within the fragment, i try to access it from outside.

JamMaster
  • 1,446
  • 1
  • 14
  • 24
  • `getView` returns the view you inflated in `onCreateView` and you can't really be sure, since the process is somehow asynchronous, when it will happen. – Blackbelt Jul 24 '14 at 12:37
  • *i try to access it from outside* - you shouldn't do this because fragments should be self contained units. *but it returns null.* - fragment transactions are asynchronous operations, they are scheduled to happen in the future not right away. Trying to access the fragment's view right after calling `show()` will not work. Pass the Image resource to the fragment through a bundle(`setArguments()`) and let it set the image inside. – user Jul 24 '14 at 12:38
  • @Luksprog I tried passing the imageResource through a Bundle to the fragment and then assigning the image using resIcon.setImageResource(this.getArguments().getInt("image")), but it didn't work. I also tried doing this in onCreateView instead of onCreateDialog, same result. – JamMaster Jul 24 '14 at 12:51
  • It didn't worked is not very helpful when trying to solve a bug. In the `onCreateDialog()` method, when you build the view for the dialog, look for the `ImageView` in that inflated view and set the image. – user Jul 24 '14 at 14:08
  • @Luksprog It worked. It didn't work before because I was calling getView instead of using the existing one in the onCreateDialog. Thank you. – JamMaster Jul 24 '14 at 14:57

1 Answers1

0

A Fragment's view is not loaded until its onCreateView() method is invoked (see the Fragment lifecycle: http://developer.android.com/guide/components/fragments.html). You really shouldn't try to update a Fragment's view like you are trying to. Set the image inside your Dialog Fragment's onCreateView() instead. Use setArguments() and getArguments() to pass a specific resource ID (see passing argument to DialogFragment).

Community
  • 1
  • 1
0101100101
  • 5,786
  • 6
  • 31
  • 55