5

I made an application where I dynamically add and delete a textView to a LinearLayout every time a button is pressed.

My problem is that when the screen orientation changes, which re-starts the activity, all the textViews added disappear. I don't know how to retain the LinearLayout inflated state.

This is the part of the code where I initialize the views and the 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 on the onClick method I add or delete the 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);
            }
        }
    }
toplusde
  • 63
  • 4

2 Answers2

1

you can alleviate the burden of reinitializing your activity by retaining a Fragment when your activity is restarted due to a configuration change. This fragment can contain references to stateful objects that you want to retain.

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

To retain stateful objects in a fragment during a runtime configuration change:

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

2-Call setRetainInstance(boolean) when the fragment is created.

3-Add the fragment to your activity.

4-Use FragmentManager to retrieve the fragment when the activity is restarted.

More details are here

bilal
  • 2,187
  • 3
  • 22
  • 23
  • I haven't tried using a fragment for this specific app. I was not sure if it's possible to mix fragments and inflation. I will try it though. – toplusde Aug 30 '15 at 18:24
0

When you rotate your screen the activity is destroyed and recreated. You need to save your activity state to retain any data.

See here Have a look here Saving Android Activity state using Save Instance State

Community
  • 1
  • 1