Vid*_*nes 29 android android-layout android-webview
我正在尝试从布局main.xml设置WebView的URL.
通过代码,它很简单:
WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/index.html");
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法将此逻辑放入布局XML文件中?
小智 6
您可以声明自定义视图并应用自定义属性,如此处所述。
结果看起来类似于:
在你的布局中
<my.package.CustomWebView
custom:url="@string/myurl"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
Run Code Online (Sandbox Code Playgroud)
在你的 attr.xml 中
<resources>
<declare-styleable name="Custom">
<attr name="url" format="string" />
</declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)
最后在您的自定义 Web 视图类中
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*ego -5
由于 URL 基本上是一个字符串,因此您可以将其放入 value/strings.xml 文件中
<resources>
<string name="myurl">http://something</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(getString(R.string.myurl));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30166 次 |
最近记录: |