addToBackState()不会恢复片段状态

时间:2013-07-23 08:27:56

标签: java android android-fragments fragmenttransaction

当我将fragmentA替换为fragmentB时,我使用此代码:

 fragmentManager
        .beginTransaction()
        .replace(R.id.content_frame, new fragmentB())
        .addToBackStack(null)
        .commit();

但是当我按下后退按钮fragmentA时,它不会保持其先前的状态,而是从头开始重新加载。 如何恢复以前的fragmentA状态?

1 个答案:

答案 0 :(得分:0)

您可以尝试覆盖片段的onSaveInstanceState(Bundle outState)方法。只需将webview的当前url保存到bundle中,然后在片段的onCreateView方法中检索它。

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    ...
    if(savedInstanceState != null){
        String url = savedInstanceState.getString("URL");
        if(url != null){
            mWebView.loadUrl(url);
        }
    }
    ...
}

public void onSaveInstanceState(Bundle outState){ 
    super.onSaveInstanceState(outState);
    outState.putString("URL", mWebView.getUrl();
}