我想在片段中创建可编辑的文本字段,在保存关闭或停止应用程序之后。但是返回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的内容但它没有保存任何东西。
答案 0 :(得分:3)
更改为
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
初始化它。
答案 1 :(得分:1)
更改
EditText notatki = (EditText) view.findViewById(R.id.editText1);
到
notatki = (EditText) view.findViewById(R.id.editText1);
因为如果你在onCreateView
中再次声明它会影响全局的那个,你会在onStop
答案 2 :(得分:0)
试试这个......
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details2, parent, false);
EditText notatki = (EditText) view.findViewById(R.id.editText1);
SharedPreferences settings = this.getActivity().getSharedPreferences("PREFS", 0);
notatki.setText(settings.getString("value", ""));
return view;
}
答案 3 :(得分:0)
你做得对,但问题是你应该从onCreateView
返回父视图而不是EditText实例notatki
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details2, parent, false);
....
return view;
}
答案 4 :(得分:0)
private EditText etext;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.secondfragment,container,false);
etext = (EditText) getView().findViewById(R.id.editText4);
return v;