我的EditText在方向更改方面遇到了一些问题。出于某种原因,他们不会恢复输入的内容。 我有2节课。主要活动和活动中的片段 主要活动:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(
setContentView(R.layout.
getFragmentManager().beginTransaction().replace(R.id.controlsBar, new AddItemFragment()).commit();
}
}
片段:
public class AddItemFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_item, container, false);
EditText item = (EditText) view.findViewById(R.id.itemNameAdd);
EditText amount = (EditText) view.findViewById(R.id.itemAmount);
if (savedInstanceState != null) {
System.out.println(savedInstanceState.getString("item"));
item.setText(savedInstanceState.getString("item", ""));
amount.setText(savedInstanceState.getString("amount", ""));
}
//item.setText("SOME TEXT");
//amount.setText("SOME TEXT");
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
EditText item = (EditText) getActivity().findViewById(R.id.itemNameAdd);
EditText amount = (EditText) getActivity().findViewById(R.id.itemAmount);
outState.putString("item", item.getText().toString());
outState.putString("amount", amount.getText().toString());
}
}
有趣的是该行" System.out.println(savedInstanceState.getString(" item"));"在控制台中打印出正确的单词。 此外,我将文本设置为" SOME TEXT"也有效。 它只有当我将文本设置为savedInstanceState.getString(" amount","")时,它才会工作
谢谢
答案 0 :(得分:0)
尝试添加标记为"< ---- THIS LINE"到public void onSaveInstanceState(Bundle outState)
:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); // <---- THIS LINE
EditText item = (EditText) getActivity().findViewById(R.id.itemNameAdd);
EditText amount = (EditText) getActivity().findViewById(R.id.itemAmount);
outState.putString("item", item.getText().toString());
outState.putString("amount", amount.getText().toString());
}
另外,请查看使用onActivityCreated
,并查看下面评论中的资源。