在Android中,动态添加的视图在屏幕方向改变时消失了。

8

我已经创建了视图,通过按钮点击可以动态添加到布局中,但是当我将设备旋转为横向时,这些视图会消失。请问有人能够查看我的代码并解释如何防止发生这种情况吗?

代码如下:

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

}

}
3个回答

5
请将以下内容添加到您的manifest.xml标签中。
android:configChanges="keyboardHidden|orientation|screenSize"

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

应该在<activity>标签中添加。 - Homayoon Ahmadi

1

最好尝试在新的方向中重新创建布局,而不仅仅是防止方向更改。

在onCreate方法中检查是否有保存的实例(由于方向更改而产生),例如:

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

你可能需要保留一些值(无论是在共享首选项还是onSavedInstanceState中)。
这种方法比锁定方向更困难,但从长远来看是更好的方法,值得投入研究。

-1
将以下行添加到TestContainerActivity活动中:
android:ConfigChanges="keyboardHidden|orientation"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接