我創建了從按鈕單擊動態添加到佈局的視圖,但是當旋轉設備環境時,視圖消失。有人可以看看我的代碼,並解釋如何阻止這種情況發生。動態添加的視圖在Android中的方向上消失
下面是代碼:
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);
}
}