我试图在屏幕旋转后重新创建视图, 她加入了#34; 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();
}
}
答案 0 :(得分:1)
将此添加到您的清单
<activity
android:name=".TestFragmentActivity"
android:configChanges="orientation">
</activity>
答案 1 :(得分:0)
如果在Manifest文件中定义android:configChanges =“orientation”,则无需调用onConfigurationChanged()方法,因为Activity将自动管理方向更改时的当前状态和内容。