我试图防止在旋转变化时丢失webview状态,这是我的片段代码:
public class ContentFragment extends Fragment {
private String mArticleId, imageUrl;
private WebView mContent;
private ImageView mBackground;
private LinearLayout mLayout;
private Bundle webViewBundle;
public static ContentFragment newInstance(String idcko) {
ContentFragment f = new ContentFragment();
Bundle args = new Bundle();
args.putString("idcko", idcko);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
mArticleId = getArguments().getString("idcko");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_content, null);
mContent = (WebView) root.findViewById(R.id.content_web);
if (webViewBundle == null) {
new FetchContent().executeOnExecutor(
AsyncTask.THREAD_POOL_EXECUTOR, "");
} else {
Log.e("else", "");
mContent.restoreState(webViewBundle);
}
return root;
}
@Override
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
mContent.saveState(webViewBundle);
}
private class FetchContent extends AsyncTask<String, String, String> {
private JSONParser jsonParser;
private String content;
@Override
protected String doInBackground(String... params) {
jsonParser = new JSONParser();
List<NameValuePair> parametre = new ArrayList<NameValuePair>();
parametre.add(new BasicNameValuePair("post_id", mArticleId));
JSONObject jObj = jsonParser
.getJSONFromUrlNonHtml(
"http://www.androidaci.net/api/get_post/",
parametre, "GET");
try {
JSONObject post = jObj.getJSONObject("post");
content = post.getString("content");
} catch (JSONException e) {
e.printStackTrace();
}
return content;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mContent.loadDataWithBaseURL("", removePlayStore(result),
"text/html", "UTF-8", "");
}
}
我以HTML格式加载网站上的内容,我用JSOUP对其进行了一些修改,然后我展示了它,它首先尝试使用,但是在轮换更改后我松开了状态。我怎么能保存这个?
答案 0 :(得分:0)
为了使此代码有效,我需要从onCreate
this.setRetainInstance(true);