2012-06-01 102 views
0

我正在开发一个动态创建控件的Android应用程序。我做了这种类型的编码。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" 

当我从纵向更改方向为横向它的作品好。但从风景到肖像应用程序崩溃了。部队关闭。

任何建议我的代码?????

+0

如果你说它崩溃了,请添加你的logcat ..只要你的应用程序崩溃,你肯定会得到一个崩溃日志。 – Ghost

回答

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