[英]Android Handling orientation changes - no change if rotation occurs
我在適應方向時遇到問題。
我在運行該應用程序時會加載的活動中有一個片段。
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
輸出:(默認方向-縱向)
但是,當我將手機旋轉到橫向時,它只是增加了片段。
輸出:
有什么辦法可以解決這個問題? 我一直在閱讀有關在運行時處理旋轉的一些問題,但是他們的解決方案是禁用定向。 也有人說使用AsyncTask函數來處理此問題。 我是android的新手,而其他android庫還不熟悉。 謝謝回答。
屏幕旋轉不會破壞您之前的片段,而是保存並恢復其狀態。
我猜想您在Activity的onCreate
方法中調用了fragmentTransaction
邏輯,因此每次恢復該活動時,它都會在舊的片段上添加一個新的片段。
您可以通過檢查onCreate()
方法上的savedInstanceState
Bundle是否為null來避免這種情況,這樣,在重新創建活動時就不會添加新的片段,如下所示:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if(savedInstanceState == null) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
}
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.