How do I set URL for WebView from layout XML in Android?
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();
}
}
}
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"/>