Android 在 WebView 中打开 URL [英] Android open URL in WebView
问题描述
我首先创建了 Android 测试应用.
I'm firstly create Android Test App.
我使用的是 webview 表单,我插入了一些 url,当我运行应用程序时,它工作正常.
I'm using webview form, and I'm insert some url, and when I'm running app its work fine.
但是当我打开应用程序并单击其他页面链接时,我会得到选择的列表,例如,在Google Chrome"上打开它.但我想在 webview 中打开它.
But when I'm open app, and click some other page link, than I get chosen list, example, open it on "Google Chrome". But I want to open it in webview.
我认为解释得很清楚.
activity_mail.xml
activity_mail.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp" tools:context=".MainActivity">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
MainActivity.java
MainActivity.java
package com.example.webviewapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://example.com";
WebView view=(WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
}
}
谢谢!
推荐答案
您需要创建一个 WebViewClient
You need to Create a WebViewClient
并覆盖shouldOverrideUrlLoading()
方法
试试这个:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) findViewById(R.id.webView1);
view.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("http://example.com");
}
来自 shouldOverrideUrlLoading
当新的应用程序出现时,给宿主应用程序一个接管控制权的机会url 即将加载到当前的 WebView 中.如果 WebViewClient 是未提供,默认情况下 WebView 会要求活动管理器选择url 的正确处理程序.如果提供了 WebViewClient,则返回true 表示宿主应用程序处理 url,而返回 false表示当前 WebView 处理 url.
Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.
这篇关于Android 在 WebView 中打开 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!