我試圖在屏幕旋轉後重新創建視圖, 她向活動添加了「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();
}
}
在Android中,活動將在方向更改期間被默認重新創建。所以視圖將被重新創建。沒有處理需要的。這不是在發生嗎?爲什麼在預期默認行爲時處理它? – VishnuSP