Search code examples
javaandroidandroid-fragmentsandroid-activityviewgroup

Dynamically Add View To Fragment Outside OnCreateView Call


I have looked at about 12 SO posts, and read the documentation on both Activities and Fragments.

I have what I think is an incredibly common issue but perhaps I'm missing something fundamental.

I have a fragment. This fragment is creating its view from Java not from XML. During runtime, I want to add an image to it. I've tried adding the view to the viewgroupd, creating a LinearLayout and adding it to the view, and a few other things but none of them work. I often get a crash (with NO error log :?().

Here is my best attempted code:

iImage image = new iImage(getActivity());
image.setImageResource(R.drawable.image);
LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
image.setLayoutParams(imageParams);
((ViewGroup)getFragmentManager().findFragmentById(resourceId).getView()).addView(image);

If you can advise how I can just add a view to the fragment I would GREATLY appreciate it!


Solution

  • You have an incredibly common problem. The solution is to keep a private variable to your inflated view and you can use it later... where ever that may be. In this example I am assuming that your root layout (the top most element in your XML) is LinearLayout

    public class DummyFragment extends Fragment {
    
        private LinearLayout root;
    
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            LinearLayout = (LinearLayout)  inflater.inflate(R.layout.dummy_fragment_layout, container, false);
            return root;
        }
    
    }