我为同一片段创建了2种不同的布局。一个用于Portrait
,第二个用于Landscape
。我有一个EditText
字段,如果我更改了方向,我想要传递的内容,因此布局会切换。该值将被保存,并在调用onViewCreated
时在Log.d中打印出来,但未在EditText
字段中设置。
我也注意到,它只是在第一次保存,并且每次更改时捆绑都会成倍增加。运行时中的任何其他输入都将被忽略。
接下来:
02-07 10:26:15.100 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:18.780 9968-9968/parohyApps.antdiary I/System.out: 2131492950
02-07 10:26:23.300 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:23.340 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:24.430 9968-9968/parohyApps.antdiary W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
02-07 10:26:25.570 9968-9968/parohyApps.antdiary W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
02-07 10:26:32.380 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:32.400 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:32.430 9968-9968/parohyApps.antdiary D/NewData: Bundle string > hi
02-07 10:26:32.550 9968-9968/parohyApps.antdiary I/Choreographer: Skipped 78 frames! The application may be doing too much work on its main thread.
代码:
public class NewData extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_data_layout, container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState != null){
Log.d("NewData", "Bundle string > " + savedInstanceState.getString("outString", "NO STRING"));
EditText name = (EditText) view.findViewById(R.id.et_name);
name.setText(savedInstanceState.getString("outString",
"NO STRING"));
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
EditText name = (EditText) getActivity().findViewById(R.id.et_name);
outState.putString("outString",name.getText().toString());
}
}
答案 0 :(得分:1)
我认为您需要将片段保存在活动的onSaveInstanceState
和onRestoreInstanceState
中,例如:
保存片段
public void onSaveInstanceState(Bundle outState){
getFragmentManager().putFragment(outState,"yourFragment",yourFragment);
}
恢复片段
public void onRestoreInstanceState(Bundle inState){
yourFragment = getFragmentManager().getFragment(inState,"yourFragment");
}