我想在片段中创建可编辑的文本字段,直到关闭或停止应用程序后才能保存.但是,与notatki返回相符的地方出了问题;我已经有这个了:
public class DetailFragment2 extends Fragment {
private EditText notatki;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
@SuppressLint("SimpleDateFormat")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details2, parent, false);
notatki = (EditText) view.findViewById(R.id.editText1);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
notatki.setText(settings.getString("value", ""));
return view;
}
@Override
public void onStop( ){
super.onStop();
if(notatki.getText() != null) {
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("value", notatki.getText().toString());
editor.commit();
}
}
}
当我改变返回notatki;返回视图;当我想保存editText的内容时,它一直工作到应用程序停止,但它并没有保存任何内容.
解决方法:
改成
private EditText notatki;
@SuppressLint("SimpleDateFormat")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details2, parent, false);
notatki = (EditText) view.findViewById(R.id.editText1);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
notatki.setText(settings.getString("value", ""));
return view; // return view here instead of notaki
}
您已经声明EditText为类成员
private EditText notatki;
因此,只需在onCreateView中对其进行初始化.