Skip to content
Advertisement

Adding a linear layout in XML dynamically to another linear layout

Basically I created a separate XML containing a linear layout which contains a image and a textview, and I need this linear layout inside of another linear layout, where I need to add my first linear layout dynamically to the second linear layout.

First linear layout, a separate XML file :

JavaScript

Second linear layout, separate XML:

JavaScript

Android Studio code:

JavaScript

This doesn’t work, I am getting a null pointer exception :

JavaScript

What can I try to resolve this?

Advertisement

Answer

One of the layouts must not exist as a view yet. If your activity or fragment is being built with settingButtonHolder layout then you need to inflate the other layout using a LayoutInflater.

Once you’ve used the LayoutInflater you will receive a view instance which you can use to add to your linearlayout in the place of linearLayout2. Until you’ve inflated your new layout, you will keep seeing NPEs because the views in that layout will not exist. You will have to use your inflated view instance (linearLayout2) to access the views, preferably through linearLayout2.findViewById(R.id.X).

Try this out and let me know if it has helped you at all, Panos.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement