2017-06-23 87 views
0

我試圖在屏幕旋轉後重新創建視圖, 她向活動添加了「TestFragment」,屏幕旋轉onConfigurationChange()被調用,在此我執行setcontextview()以便重新創建視圖並嘗試用相同的實例替換現有的「TestFragment」。 但片段沒有添加,我可以知道這個代碼中有什麼問題。配置更改後未添加片段

public class TestFragmentActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     Log.d("Test", "onCreate"); 
     setContentView(R.layout.activity_test); 
     createFragment(); 
    } 

    private void createFragment(){ 
     Fragment fragment = getSupportFragmentManager().findFragmentByTag("TestFragment"); 
     if (fragment == null) { 
      Log.d("Test", "not found"); 
      fragment = new TestFragment(); 

     }else { 
      Log.d("Test", "found"); 
     } 
     FragmentTransaction fragmentTransaction; 
     fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
     fragmentTransaction.replace(R.id.frame1, fragment, "TestFragment"); 
     fragmentTransaction.addToBackStack(null); 
     fragmentTransaction.commitAllowingStateLoss(); 
     getSupportFragmentManager().executePendingTransactions(); 
    } 


    @Override 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 
     Log.d("Test", "onConfigurationChanged"); 
     setContentView(R.layout.activity_test); 
     createFragment(); 
    } 
} 

    public class TestFragment extends Fragment { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setRetainInstance(true); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View root = inflater.inflate(R.layout.test_fragment, null, false); 
     return root; 
    } 

    @Override 
    public void onDestroy() { 
     Log.d("Test", "onDestroy TestFragment"); 
     super.onDestroy(); 
    } 
} 
+1

在Android中,活動將在方向更改期間被默認重新創建。所以視圖將被重新創建。沒有處理需要的。這不是在發生嗎?爲什麼在預期默認行爲時處理它? – VishnuSP

回答

1

添加到您的清單

<activity 
     android:name=".TestFragmentActivity" 
     android:configChanges="orientation"> 
</activity> 
+0

我已經添加android:configChanges =「orientation | screenSize」這onConfigChange被調用,問題是與片段沒有得到添加 – user1972094

0

無需調用onConfigurationChanged()方法,如果你定義的android:清單文件configChanges =「方向」,因爲活動將自動管理現狀和方向變化的內容。