How do I set URL for WebView from layout XML in Android?

Vidar Vestnes picture Vidar Vestnes · Mar 7, 2011 · Viewed 32.6k times · Source

I'm trying to set the URL for a WebView from the layout main.xml.

By code, it's simple:

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

Is there a simple way to put this logic into the layout XML file?

Answer

loklok picture loklok · Mar 22, 2017

You can declare your custom view and apply custom attributes as described here.

The result would look similar to this:

in your layout

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

in your attr.xml

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

finally in your custom web view class

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