背景:左侧有一个菜单,右侧有不同的可滚动内容。我想保存滚动位置。但我失败了。然后 ...
我已经建立了一个非常简单的项目来测试它。
换句话说,我在左边有一个菜单,不同的内容都<EditText>
在右边。(虽然属于同一类,但它们属于不同的实例)
在代码中,(非常简单)
内容.xml
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Please save my text ..." />
内容片段.java
package ... import ...
public class ContentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.content, container, false);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
System.out.println("Why this is NOT called ?");
Log.v("onSaveInstanceState()", "outState = " + outState);
}
}
和程序生成的MenuFragment.java
package ... import ...
public class MenuFragment extends ListFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new String[]{"Item 1", "Item 2", "Item 3"}));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
((MainActivity) getActivity()).click();
}
}
最后,我们的MainActivity.java
package ... import ...
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
getSupportFragmentManager().beginTransaction()
.add(R.id.menu, new MenuFragment()).commit();
}
public void click() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, new ContentFragment() // everytime load a new instance
).addToBackStack(null).commit();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
System.out.println("... and this is NOT called neither :-/");
Log.v("onSaveInstanceState()", "outState = " + outState);
}
}
要对其进行测试,请不要旋转您的设备。
首先,从菜单中选择一个项目,然后在文本框中输入一些内容。然后选择另一个项目并再次键入内容。重复几次。然后返回并...
您会发现您之前输入的文本已保存!
文本被保存并不奇怪......
但令人惊讶的是,这些文本与所有未调用的函数一起保存。onSaveInstanceState()
Android 何时保存replaced
它们FragmentTransaction
?
如果我想在每个Fragment
实例中额外保存一些数据(比如滚动位置),我应该把我的代码放在哪里?