Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically added views disappear on orientation in Android

I have created the views to be added in dynamically to a layout from a button click, but when I rotate the device landscape, the views disappear. Could someone please look at my code and explain how to stop this from happening.

Here is the code:

public class TestContainerActivity extends Activity implements OnClickListener {

LinearLayout containerLayout;
Button testButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_container);

    testButton = (Button)findViewById(R.id.testContainerButton1);
    testButton.setOnClickListener(this);        
    containerLayout = (LinearLayout)findViewById(R.id.testContainerLayout);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.test_container, menu);
    return true;
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v==testButton){

        createNewLayout();

    }
}

public void createNewLayout(){

        LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View addView = layoutInflater.inflate(R.layout.container, null);
        TextView textviewTest = (TextView)addView.findViewById(R.id.containerTextView4);
        textviewTest.setText("TextView");

        containerLayout.addView(addView);

}

}
like image 789
James Meade Avatar asked Jul 29 '13 10:07

James Meade


Video Answer


2 Answers

Add this line in your manifest.xml Tags.

android:configChanges="keyboardHidden|orientation|screenSize"

This will avoid your activity from recreating on orientation change.

like image 111
Ahmad Raza Avatar answered Oct 27 '22 17:10

Ahmad Raza


It is better to try to recreate the layout in the new orientation, rather than just preventing the orientation change.

In your onCreate check whether there is a saved instance (as a result of the orientation change) e.g.

if (savedInstanceState == null) {
      //create new button layout if previously clicked
}
else {
      //normal start
}

You might need to retain some values (either in Shared Prefs or onSavedInstanceState).

This approach is more difficult than locking the orientation, but it is a better approach in the long run and is well worth the research effort.

like image 44
IanB Avatar answered Oct 27 '22 18:10

IanB