0

我正在开发一个动态创建控件的 Android 应用程序。我做了这种类型的编码。

TextView lblTitle = new TextView(myContext);
relLayoutHeader.addView(lblTitle);

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig); 
   if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
       lblTitle.settext("LandScape");
   } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
       lblTitle.settext("Portrait");
}

在清单文件中:

android:configChanges="orientation|keyboardHidden"

当我将方向从纵向更改为横向时,效果很好。但是从横向到纵向的应用程序崩溃了。强制关闭。

对我的代码有什么建议吗??????

4

1 回答 1

0

您需要在 重新初始化您的视图onConfigurationChanged

// used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI() {
    // get views from ID's
    relLayoutHeader = _______Initialise_here;
    TextView lblTitle = new TextView(myContext);
    relLayoutHeader.addView(lblTitle);
    // etc... hook up click listeners, whatever you need from the Views
}

// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InitializeUI();
}

// this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see:
// android:configChanges)
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);

    InitializeUI();
    //And then do your stuff
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
           lblTitle.settext("LandScape");
   } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
       lblTitle.settext("Portrait");
   }
} 
于 2012-06-01T06:58:10.870 回答