android – 如何使用片段处理方向更改?
作者:互联网
我现在有2个片段,一个片段处理纵向模式然后另一个处理横向模式.但问题是,从纵向旋转到横向然后再回到纵向.它不会显示在第一个肖像模式上显示的相同内容.有没有可以解决这个问题的代码?
此代码位于片段持有者中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag_holder);
FragmentManager fm = getSupportFragmentManager();
final Fragment fragment = Frag.newInstance(); //Portrait layout
final Fragment fragment2 = Frag2.newInstance(); //Landscape layout
int orientation = getResources().getConfiguration().orientation; //check whether is it portrait or landscape
if(orientation == Configuration.ORIENTATION_PORTRAIT){
Fragment fragTAG = fm.findFragmentByTag(TAG_P);
if(fragTAG == null){
Log.i("test","test");
fm.beginTransaction()
.replace(R.id.fragPlaceHolder, fragment, TAG_P)
.commit(); //Portrait
}
else{
fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
}
}
if(orientation == Configuration.ORIENTATION_LANDSCAPE){
Fragment fragTAG = fm.findFragmentByTag(TAG_L);
if(fragTAG == null){
fm.beginTransaction()
.replace(R.id.fragPlaceHolder, fragment2, TAG_L)
.commit(); //Landscape
}
else{
fm.beginTransaction().replace(R.id.fragPlaceHolder,fragTAG).commit();
}
}
}
}
解决方法:
步骤1:
在活动中添加配置更改
<activity android:name=".ui.createtasks.CreateTaskActivity"
android:configChanges="orientation|screenSize|keyboardHidden" > </activity>
第2步:
将编辑文本值添加到onSaveInstanceState
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putCharSequence(KEY_TITLE, et_text.getText().toString());
}
第3步:
通过onViewStateRestored获取已保存的编辑文本值
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
String savedTitle = null;
if (savedInstanceState != null) {
savedTitle = savedInstanceState.getString(KEY_TITLE);
et_text.setText(savedTitle);
}
}
标签:android-orientation,android,android-fragments 来源: https://codeday.me/bug/20190829/1757625.html