我有一个活动,我已经为注册过程放了5个片段。第一个片段有两个编辑文本和一个textview。编辑文本用于名字和姓氏,文本视图将我带到下一个fragment2。当我从frag2返回到frag 1时,那些名字和姓氏值消失了。我尝试使用putString方法在onSavedInstance方法中存储值,并在onCreate方法中检索它,但它没有帮助。这是代码......
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
}
else{
firstName=savedInstanceState.getString("firstname");
lastName=savedInstanceState.getString("lastname");
fname.setText(firstName);
lname.setText(lastName);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag1,container,false);
fname = (EditText) rootView.findViewById(R.id.si_firstname);
lname = (EditText) rootView.findViewById(R.id.si_lastname);
firstName = fname.getText().toString();
lastName = lname.getText().toString();
next1 = (TextView) rootView.findViewById(R.id.next1);
next1.setOnClickListener(new View.OnClickListener() { //takes to frag2.
@Override
public void onClick(View v) {
if(firstName.isEmpty() || lastName.isEmpty()){
Toast.makeText(getActivity().getApplicationContext(), "no name", Toast.LENGTH_LONG).show();
}
else {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, secondFragment);
fragmentTransaction.commit();
}
}
});
return rootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("firstname", firstName);
outState.putString("lastname", lastName);
}
答案 0 :(得分:1)
而不是
fragmentTransaction.replace(R.id.fragment_container, secondFragment);
使用
fragmentTransaction.add(R.id.fragment_container, secondFragment);
修改强>
如果这不起作用,那么您必须在交易中使用addToBackstack
,这肯定会有效。但是,您还需要覆盖Main活动中的onBackPressed
函数和popbackStack以弹出片段,然后返回上一个片段。 This是您需要覆盖它的方式。
答案 1 :(得分:0)
您似乎正在使用onCreate
中设置的值覆盖您在onCreateView
内获得的savedInstance数据。尝试在onCreate
中注释掉代码并将onCreateView
内的顶行替换为:
View rootView = inflater.inflate(R.layout.frag1,container,false);
fname = (EditText) rootView.findViewById(R.id.si_firstname);
lname = (EditText) rootView.findViewById(R.id.si_lastname);
next1 = (TextView) rootView.findViewById(R.id.next1);
if(savedInstanceState != null){ //the data's on the savedinstance
firstName = savedInstanceState.getString("firstname");
lastName = savedInstanceState.getString("lastname");
//restore the editTexts
fname.setText(firstName);
lname.setText(lastName);
}else{
firstName = fname.getText().toString();
lastName = lname.getText().toString();
//whatever you want to do on the first run
//or if the data's not on the savedInstance
}
//whatever else you want to do on every run