我正在尝试从布局 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/