我在這裏有幾個片段,這裏有一個片段,當我回到它時,我想保存它的狀態。我試着在testfragment中做這件事,當我點擊按鈕時,textview文本將變爲「test1」(textview的默認文本是「New Text」)。所以textview改變了文本,但是當我移動到另一個片段並回到它(HomeFragment
)時,textview將轉到它的默認狀態文本(「New Text」)。所以我認爲savedInstanceState
不能正常工作,因爲如果有的話,當我回到片段時它應該有「test1」。這裏是我的代碼:片段savedInstanceState不起作用
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);
}
}
'onActivityCreated'運行** **後'onCreateView',所以你重寫TextView的文本。 – EpicPandaForce
感謝您注意我的帖子,@EpicPandaForce。所以我應該先把OnCreateView放在OnCreateView上。這是你的建議嗎? – IWantToBeAnAnonymous
不,你應該將'if(savedInstance == null)'東西移到'onActivityCreated'方法中(實際上,你應該把整個東西移動到'onViewCreated()') – EpicPandaForce