我在这里和那里有几个片段这个片段我想在它回到它时保存它的状态。我尝试在testfragment中进行,当我单击按钮时,textview文本将更改为" test1"(textview的默认文本为" New Text")。因此textview会更改文本,但是当我移动到另一个片段并返回它(HomeFragment
)时,textview将转到其默认状态文本(" New Text")。所以我认为savedInstanceState
不起作用,因为如果确实如此,它应该有" test1"当我回到片段。这是我的代码:
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);
}
}
答案 0 :(得分:0)
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);
}
}