我已经创建了要通过单击按钮动态添加到布局中的视图,但是当我旋转设备景观时,视图消失了。有人可以看看我的代码并解释如何阻止这种情况发生。
这是代码:
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);
}
}