雅。您必須在此課程中實施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