2012-03-06 67 views
5

我有一个网站。在网站上有一个文字“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; 
} 

} 
} 

回答

1

我会用WebViewClient.shouldInterceptRequest()

通知资源请求的主机应用程序并允许 应用程序返回数据。如果返回值为空,则WebView将继续像平常一样继续加载资源。否则,将使用 返回响应和数据。

注意:此方法在 之外的线程上调用,因此客户端在访问私人数据或视图系统时应谨慎行事 。

+0

来自shouldInterceptRequest的javadoc,它表示它返回一个包含响应信息的WebResourceResponse,或者如果WebView应该加载资源本身,则返回null。我不明白它与重写html有什么关系。 – kevin 2014-02-24 23:32:09

+0

@kevin你可以自己加载页面,重写它的源代码并将其作为'WebResourceResponse'返回。 – user11153 2015-10-30 10:24:01