如何在Android中从布局XML设置WebView的URL?

Vid*_*nes 29 android android-layout android-webview

我正在尝试从布局main.xml设置WebView的URL.

通过代码,它很简单:

WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/index.html");
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法将此逻辑放入布局XML文件中?

小智 6

您可以声明自定义视图并应用自定义属性,如此处所述

结果看起来类似于:

在你的布局中

<my.package.CustomWebView
        custom:url="@string/myurl"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>
Run Code Online (Sandbox Code Playgroud)

在你的 attr.xml 中

<resources>
    <declare-styleable name="Custom">
        <attr name="url" format="string" />
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

最后在您的自定义 Web 视图类中

    public class CustomWebView extends WebView {

        public CustomWebView(Context context, AttributeSet attributeSet) {
            super(context);

            TypedArray attributes = context.getTheme().obtainStyledAttributes(
                    attributeSet,
                    R.styleable.Custom,
                    0, 0);
            try {
                if (!attributes.hasValue(R.styleable.Custom_url)) {
                    throw new RuntimeException("attribute myurl is not defined");
                }

                String url = attributes.getString(R.styleable.Custom_url);
                this.loadUrl(url);
            } finally {
                attributes.recycle();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 您仍在使用代码。这比他发布的 3 行代码要工作得多。不? (4认同)

Pet*_*ego -5

由于 URL 基本上是一个字符串,因此您可以将其放入 value/strings.xml 文件中

<resources>
    <string name="myurl">http://something</string>
</resources>
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(getString(R.string.myurl));
Run Code Online (Sandbox Code Playgroud)

  • 我认为他正在尝试找到某种方法来直接在 xml 文件中设置 url,而不必在 Activity 中运行方法 loadUrl。例如: &lt;Webview android:url="@string/my_url" /&gt; (36认同)
  • 这不应该是一个选定的答案。它没有回答这个问题。 (23认同)