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);
}
}
Add this line in your manifest.xml Tags.
android:configChanges="keyboardHidden|orientation|screenSize"
This will avoid your activity from recreating on orientation change.
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.
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