依赖指向 UI 组件的静态变量(如 a TabHost
)会导致内存泄漏。不要这样做。而是在 中注册一个BroadcastReceiver
以TabActivity
添加新选项卡。这样,您无需修改静态变量,而是发送广播 ( Context#sendBroadcast(Intent)
) 来告诉选项卡活动您想要一个新选项卡。
此外,请确保保存 的状态TabActivity
,以便在 Android 操作系统因某种原因破坏您的活动时可以恢复它。我建议使用onRetainNonConfigurationInstance
... 像这样的东西:
private State mState;
public void onCreate(Bundle b){
// somewhere in onCreate
mState = (State) getLastNonConfigurationInstance();
if( mState == null ){
mState = new State();
} else {
for(TabSpec tab : mState.tabs){
//add them to the tab host
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mState;
}
private static class State{
List<TabSpec> tabs;
// more stuff that you want to save
}