背景:我在左邊有一個菜單,右邊有不同的可滾動內容。我想保存滾動的位置。但我失敗了。然後...FragmentTransaction.Replace在哪裏片段保存其狀態?
我設置了一個非常簡單的項目來測試它。
換句話說,我在左邊有一個菜單,不同的內容全部在右邊持有<EditText>
。 (儘管是同一類的,它們是不同的實例)
在碼,(非常簡單)
的content.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 ..." />
ContentFragment.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
實例(如滾動位置),我應該在哪裏把我的代碼?
另外,我發現了'Bundle'在'Fragment.onSaveInstanceState()'總是'null'(即使當屏幕旋轉時,或稱爲'FragmentManager.saveFragmentInstanceState()')。這對我來說很奇怪。你能解釋一下嗎? – midnite 2013-04-07 09:51:42
隨着[源代碼](https://android.googlesource.com/platform/frameworks/support/+/master/v4/java/android/support/v4/app),它解決了:) – midnite 2013-06-06 02:02:56