最後一個鏈接沒有打開,而從其他標籤返回 並且onPause()不起作用。它顯示空指針異常,並且應用程序自動關閉除第一個標籤之外的其他標籤。 片段標籤代碼onSaveInstanceState不起作用
public class FragmentTab extends Fragment {
protected WebView myWebView;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container, false);
WebView myWebView = (WebView) v.findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
if(savedInstanceState != null)
myWebView.restoreState(savedInstanceState);
else
myWebView.loadUrl("http://www.example.com");
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
myWebView.saveState(outState);
}
}
,這裏是在MainActivity
public class MainActivity extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator(null,ContextCompat.getDrawable(this,R.drawable.home)),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator(null,ContextCompat.getDrawable(this,R.drawable.deals_offers)),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator(null,ContextCompat.getDrawable(this,R.drawable.profile)),
FragmentTab.class, null);
mTabHost.addTab(
mTabHost.newTabSpec("tab4").setIndicator(null, ContextCompat.getDrawable(this, R.drawable.menu)),
FragmentTab.class, null);
}
}
我總是用setRetainInstance(真);爲了避免在配置更改後重新創建片段 –
無變化!在使用setRetainInstance(true)後; –
將myWebview和clientWebView定義爲片段頂部的靜態字段並使用保留狀態 –