【问题标题】:Dynamically added views disappear on orientation in Android动态添加的视图在 Android 中的方向消失
【发布时间】:2013-07-29 10:22:21
【问题描述】:

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

代码如下:

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

}

}

【问题讨论】:

    标签: android dynamic view orientation layout-inflater


    【解决方案1】:

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

    android:configChanges="keyboardHidden|orientation|screenSize"
    

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

    【讨论】:

      【解决方案2】:

      最好尝试以新方向重新创建布局,而不是仅仅阻止方向更改。

      在您的 onCreate 中检查是否有保存的实例(由于方向更改),例如

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

      您可能需要保留一些值(在 Shared Prefs 或 onSavedInstanceState 中)。

      这种方法比锁定方向更难,但从长远来看,它是一种更好的方法,非常值得研究。

      【讨论】:

        【解决方案3】:

        将以下行添加到 TestContainerActivity 活动

        android:ConfigChanges="keyboardHidden|orientation"
        

        【讨论】:

          猜你喜欢
          • 2011-01-05
          • 1970-01-01
          • 2011-12-22
          • 1970-01-01
          • 2011-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多