我創建了兩個片段。第二個片段包含多個edittext。 SharedPreference運行良好,但只在最後一個編輯文本上。對於剩下的,它不保存任何東西。最後,當我們在edittext中編寫,然後再次保存並運行時,應用程序仍會顯示以前保存的日期。Sharedpreferences片段
EditText et;
public TwoFragment() {
// Required empty public constructor
}
@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.fragment_two, container, false);
et =(EditText) view.findViewById(R.id.strength_score);
et =(EditText) view.findViewById(R.id.strength_modif);
et =(EditText) view.findViewById(R.id.strength_tem_scor);
et =(EditText) view.findViewById(R.id.strength_tem_modi);
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", Context.MODE_PRIVATE);
et.setText(setting.getString("value", ""));
// Inflate the layout for this fragment
return view;
}
public void onStop(){
super.onStop();
if(et.getText() != null) {
SharedPreferences setting = this.getActivity().getSharedPreferences("PRESS", 0);
SharedPreferences.Editor editor = setting.edit();
editor.putString("value", et.getText().toString());
editor.commit();
}
}
}
感謝您的幫助。
你有4個edittexts具有相同的名稱,最終,你會改變只有最後一個文本..? – DAVIDBALAS1
您需要爲不同的EditText使用不同的對象。 – NarendraJi
您是否嘗試過使用EventBus在兩個片段之間或活動和片段之間進行通信? – DJO