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

标签 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");

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

最佳答案

您可以声明您的自定义 View 并应用自定义属性,如 here 所述.

结果类似于:

在您的布局中

<my.package.CustomWebView
        custom:url="@string/myurl"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

在 attr.xml 中

<resources>
    <declare-styleable name="Custom">
        <attr name="url" format="string" />
    </declare-styleable>
</resources>

终于在你的自定义网页 View 类中

    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();
            }
        }
    }

关于android - 如何从 Android 中的布局 XML 设置 WebView 的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5219794/

相关文章:

java - 如何在服务中创建 XWalkView?

android - 从 HTML 引用 Assets 中的图像不起作用

android - 无法在android中的真实设备的内部存储中找到文件

java - 资源编译失败错误: mismatched tag

android - Facebook Android 应用程序新闻提要布局

Android游戏编程大布局

android - 我怎样才能在数字时钟中设置时间

android - WebView 显示 .pkg 文件而不是下载它

android gradle 错误 :Unable to find module with Gradle path ':libs' (needed by module 'app' . )

android - 在 android build.gradle 文件中添加任何新的依赖项。它总是显示错误