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

34,728

Solution 1

Since URL is basically a string, you can put it into values/strings.xml file

<resources>
    <string name="myurl">http://something</string>
</resources>

then you can use it like this:

WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(getString(R.string.myurl));

Solution 2

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

Solution 3

With Kotlin and binding adapter you can create a simple attribute for the Webview

Create file BindingUtils.kt

@BindingAdapter("webViewUrl") <- Attribute name
fun WebView.updateUrl(url: String?) {
    url?.let {
        loadUrl(url)
    }
}

and in the xml file: app:webViewUrl="@{@string/licence_url}"

        android:id="@+id/wvLicence"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        **app:webViewUrl="@{@string/licence_url}"**
        tools:context=".LicenceFragment"/>
Share:
34,728
Vidar Vestnes
Author by

Vidar Vestnes

I'm focused on mobile platform applications. Android apps: WriteDiary Zedge Website: HelseSmart (Norwegian) ORGi (Norwegian) More details about me at LinkedIn

Updated on August 25, 2020

Comments

  • Vidar Vestnes
    Vidar Vestnes over 3 years

    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?