android - 将 webview 嵌入到另一个 View 中

标签 android android-webview

我的应用程序有 2 个 View :

一个。 res/layout/main.xml - 带有 1 个按钮的标准 View

资源/布局/web_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
         <WebView android:id="@+id/webview"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent" />
</LinearLayout>

当我点击第一个 View (a)上的按钮时,它会加载 webview(b)并加载一个 url:

// click on the "Browser" button in view a
public void goToWebView(View view) {
        setContentView(R.layout.web_view);
        WebView mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }

一切正常,url 加载良好,但浏览器被实例化到它自己的 View 中(第三个 View ,而不是 b 本身),我的目标是使用 Webview 显示一些 HTML在单独的浏览器中将代码写入我的应用程序,而不是在应用程序之外。

有人知道吗?

这是使用 API 级别 8/Android 2.2 完成的。

感谢您的帮助。 保罗

最佳答案

其实我终于明白了。即使您以编程方式加载 url

mWebView.loadUrl("http://www.google.com");

您还必须修改默认行为(即在新浏览器实例中打开 url)。
之前的代码需要 2 处增强。

// override default behaviour of the browser
private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }  

然后,为使用 Webclient 的 View 设置新的行为:

public void goToWebView(View view) {
        setContentView(R.layout.web_view);
        WebView mWebView = (WebView) findViewById(R.id.webview);
        // add the following line ----------
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
    }

关于android - 将 webview 嵌入到另一个 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4359197/

相关文章:

java - 用户是否可以授予应用程序权限,以便该应用程序可以在需要时让设备被发现?

android - 使用 Android 应用程序的 Facebook 登录错误

android - 如何在recyclerview中加载webview?

安卓 WebView : Smaller Display Size Breaks Layout

java - 未知变量或字段 imageURL

android - webView.canGoBack() 在使用 loadDataWithBaseURL() 时不起作用

android - 如何为 Material 按钮设置渐变背景?

android - ARCore中使用ImageView显示图像

android - 录音机获取噪音水平(以分贝为单位)

android - 避免 webview 重定向