Search code examples
javaandroidsetcontentview

setContentView() deletes elements which have been added with addView()


I've 2 layouts on my project. Both have a button to swap between each other using setContentView method. Whenever I swap between these 2 layouts, every UI element I've added using addView() is lost. However static XML elements remains.


Solution

  • That's because the layout is inflated anew, with all the views specified in the xml when you call setContentView(R.layout.xml), that's happening behind the scenes, and all the dynamically added views will be gone.

    Optional solutions:

    1. Add the views again after you call setContentView().
    2. The 2 layouts can live on top of each other and you can toggle their visibility. use GONE to hide the layout, not INVISIBLE If the layouts have clickable elements on them.