How to save an overpriced layout in android after configuration changes?

I created an application in which I dynamically add and remove textView to LinearLayout every time I click a button.

My problem is that when the screen orientation changes, which restarts the activity, all added text elements disappear. I do not know how to maintain the inflated state of LinearLayout .

This is the part of the code where I initialize the views and buttons:

 private LayoutInflater inflater; private LinearLayout ll; View view; Button add; Button delete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); inflater = getLayoutInflater(); ll = (LinearLayout)findViewById(R.id.ll); add = (Button)findViewById(R.id.bAdd); delete = (Button)findViewById(R.id.bDelete); add.setOnClickListener(this); delete.setOnClickListener(this); 

and with the onClick method onClick I add or remove textViews:

  @Override public void onClick(View v) { switch (v.getId()) { case R.id.bAdd: { view = inflater.inflate(R.layout.sublayout,ll,true); break; } case R.id.bDelete: { int childSize = ll.getChildCount(); if(0 != childSize) { ll.removeViewAt(childSize -1); } Log.i("InflateLayout", "childsize: " +childSize); } } } 
+5
source share
2 answers

you can ease the burden of reinitializing your activity by saving a snippet when your activity restarts due to a configuration change. This snippet may contain references to stateful objects that you want to save.

When the Android system shuts down your activity due to a configuration change, the fragments of your activity that you marked for saving are not destroyed. You can add such fragments to your activity to save stateful objects.

To save stateful objects in a fragment during runtime configuration changes:

1 - Extend the fragment class and declare stateful references to objects.

2-Call setRetainInstance (boolean) when creating a fragment.

3-Add a fragment to your activity.

4-Use the FragmentManager to retrieve a fragment when restarting activity.

More here

+1
source

When you rotate the screen, the activity is destroyed and recreated. To save data, you need to save the activity state.

See here Look here Saving Android activity state using instance save state

0
source

All Articles