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);
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With