雅。您必须在此课程中实施WebViewClient
课程和Override
shouldOverrideURLLoading()
方法。
为什么?因为webview
只是打开你的“精确链接”,如果该链接重定向其他链接,android会为此操作打开默认浏览器。
在你的例子中,如你所知,当你连接到google.com
谷歌将重定向到谷歌在你的国家。例如,如果你在中国,谷歌将会去google.com.cn
,如果在越南,将会是google.com.vn
。
这里是我的简单的例子:(你能想象这是一个新的浏览器,:笑)
首先是布局的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<EditText
android:id="@+id/url"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="1"
android:hint="Input URL"/>
<Button
android:id="@+id/run"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="0"
android:text="GO"/>
</LinearLayout>
<WebView
android:id="@+id/webview"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
</LinearLayout>
这里是主要的活动代码:
package com.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class WebViewExample extends Activity{
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webview);
Button button = (Button) findViewById (R.id.run);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
gotoPage();
}
});
}
private void gotoPage(){
EditText text = (EditText) findViewById(R.id.url);
String url = text.getText().toString();
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webView.setWebViewClient(new Callback()); //HERE IS THE MAIN CHANGE
webView.loadUrl(url);
}
private class Callback extends WebViewClient{ //HERE IS THE MAIN CHANGE.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
}
}
希望这有助于你:)
来源
2012-03-08 04:43:21
hqt
感谢乌尔reply..but我的问题依旧相同。只要我加载到web视图的网址,它就像全新的活动或浏览器在应用程序上打开一样。点击后退按钮,它将我带到应用程序中,我可以看到2个按钮和空白的webview。 – WISH 2011-04-06 09:39:19
你能分享你的webview的父母活动中的代码......只是相关的部分。此外,启动网址的代码。 – rajath 2011-04-06 09:45:22
xml与回答相同。我的Java代码是:public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); browser =(WebView)findViewById(R.id.webView); browser.loadUrl(“http://www.google.com”); \t browser.getSettings()。setJavaScriptEnabled(true); showPrevious =(Button)findViewById(R.id.showPrevious); showNext =(Button)findViewById(R.id.showNext); }); } – WISH 2011-04-06 10:16:14