我有一個網站。在網站上有一個文字「Pic」。當我第一次在Webview中顯示網站時,我可以將文本更改爲「PicGreat」。這工作!Webview - 更改顯示網站之前的頁面源代碼?
但是,後來當用戶點擊一個鏈接(網站上的某個地方),然後我轉發用戶到新的HTML網站。在我展示網站之前,我想將文字「Pic」改爲「PicGreat」。
我該如何做到這一點?我應該寫一個函數,然後調用 「public boolean shouldOverrideUrlLoading」中的函數嗎?
我在Stackoverflow上發現了一個類似的問題,但沒有解決。 how to set webview client
main.xml中
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
AndroidManifest.xml中
<uses-permission android:name="android.permission.INTERNET" />
WebTest.java
public class WebTestActivity extends Activity {
WebView mWebView;
String rline = "";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
HttpURLConnection urlConnection = null;
try
{
URL url = new URL("http://www.picSite.com/");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader rd = new BufferedReader(new InputStreamReader(in), 4096);
String line;
while ((line = rd.readLine()) != null) {
rline += line+"\n";
}
rd.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != urlConnection)
{
urlConnection.disconnect();
}
}
String getNewCode = rline.replace("Pic", "PicGreat");
mWebView.loadData(getNewCode, "text/html", "utf-8");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
來自shouldInterceptRequest的javadoc,它表示它返回一個包含響應信息的WebResourceResponse,或者如果WebView應該加載資源本身,則返回null。我不明白它與重寫html有什麼關係。 – kevin 2014-02-24 23:32:09
@kevin你可以自己加載頁面,重寫它的源代碼並將其作爲'WebResourceResponse'返回。 – user11153 2015-10-30 10:24:01