[英]Fragment savedInstanceState not working
I have several fragments here and there's this one fragment where I want to save its state when I get back to it. 我在这里有几个片段,有一个片段想在回到它时保存其状态。 I tried doing it in a testfragment where, when I click the button, the textview text will change to "test1"(The default text of the textview is "New Text").
我尝试在一个测试片段中执行此操作,在该片段中,当我单击按钮时,textview文本将更改为“ test1”(textview的默认文本为“ New Text”)。 So the textview changes the text, but when I move into another fragment and get back to it (
HomeFragment
), the textview is going to its default state text ("New Text"). 因此,textview会更改文本,但是当我移入另一个片段并返回到它(
HomeFragment
)时,textview将返回其默认状态文本(“ New Text”)。 So I think the savedInstanceState
is not working because if it does, it should have "test1" when I get back to the fragment. 因此,我认为
savedInstanceState
不能正常工作,因为如果可以,当我回到该片段时,它应该具有“ test1”。 Here's my code: 这是我的代码:
public class HomeFragment extends Fragment {
public Button button;
public TextView txt_test;
public String data_test;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(savedInstanceState == null){
}
else{
data_test = savedInstanceState.getString("txt_test");
txt_test = (TextView) getActivity().findViewById(R.id.textView2);
txt_test.setText(data_test);
}
button = (Button) getActivity().findViewById(R.id.button3);
txt_test = (TextView) getActivity().findViewById(R.id.textView2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_test.setText("test1");
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("txt_test",data_test);
}
}
public class HomeFragment extends Fragment {
Button button;
TextView txt_test;
String data_test;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
txt_test = (TextView) view.findViewById(R.id.textView2);
button = (Button) view.findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_test.setText("test1");
}
});
if(savedInstanceState == null) {
// do nothing
} else {
data_test = savedInstanceState.getString("txt_test");
txt_test.setText(data_test);
}
return view;
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("txt_test",data_test);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.