I have a very simple question about loading layout in main activity. I have a simple layout defined in activity_main.xml which is loaded in MainActivity's OnCreate() using
setContentView(R.layout.activity_main).
Then on a button click, I add another view item (button) which shows up correctly.
But when the app is closed and opened again, I need to retain what was added last time when the app closed. How do I do that?
I searched some questions here, but most of them talk about saving values using SharedPreferences or saving state, but it is not clear if the layout can be saved as well.
Thanks in advance.
I think the best solution is saving latest state values by using SharedPreferences
, because it is a good way to save any simple data for long term.
Saving state via using saveInstanceState
is a short term solution and if you close your app completely, saved instance will be gone forever.
Possible solution:
First, you cannot save a layout as you think, but you can get the layout's parameters
and other features as variables
, then you can save these by using SharedPreferences
.
Secondly, you should check if there is any saved layout states when you start the activity. If any, you can use the pre-saved parameters for adding your layout dynamically/programmatically.