动态添加的视图在Android中的方向上消失

Jam*_*ade 6 android view dynamic orientation layout-inflater

我创建了要从按钮单击动态添加到布局的视图,但是当我旋转设备格局时,视图消失.有人可以看看我的代码并解释如何阻止这种情况发生.

这是代码:

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);

}

}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*aza 5

在您的manifest.xml标签中添加这一行。

android:configChanges="keyboardHidden|orientation|screenSize"
Run Code Online (Sandbox Code Playgroud)

这将避免您的活动在方向改变时重新创建。


And*_*ler -1

将以下行添加到TestContainerActivity活动中

android:ConfigChanges="keyboardHidden|orientation"
Run Code Online (Sandbox Code Playgroud)