Как установить URL для WebView из макета XML в Android?
Я пытаюсь установить URL для WebView из макета main.xml.
По коду это просто:
WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/index.html");
Есть ли простой способ поместить эту логику в XML файл макета?
Ответы
Ответ 1
Так как URL-адрес в основном представляет собой строку, вы можете поместить ее в файл values /strings.xml
<resources>
<string name="myurl">http://something</string>
</resources>
то вы можете использовать его следующим образом:
WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(getString(R.string.myurl));
Ответ 2
Вы можете объявить свое собственное представление и применить специальные атрибуты, как описано здесь.
Результат будет выглядеть примерно так:
в вашем макете
<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>
, наконец, в вашем пользовательском классе веб-представления
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();
}
}
}
Ответ 3
С помощью Kotlin и связующего адаптера вы можете создать простой атрибут для Webview
Создать файл BindingUtils.kt
@BindingAdapter("webViewUrl") <- Attribute name
fun WebView.updateUrl(url: String?) {
url?.let {
loadUrl(url)
}
}
и в XML файле:
Приложение: webViewUrl = "@{@строка /licence_url}"
android:id="@+id/wvLicence"
android:layout_width="match_parent"
android:layout_height="match_parent"
**app:webViewUrl="@{@string/licence_url}"**
tools:context=".LicenceFragment"/>