Weex 提供了扩展机制,可以根据自己的业务进行定制自己的功能。
主要分为两类扩展:
-keep public class * extends com.taobao.weex.common.WXModule{*;}
WXSDKEngine.registerModule("myModule", MyModule.class);
否则会报类似错误:ReportException :undefined:9: TypeError: Object #<Object> has no method 'printLog'
示例如下:
public class MyModule extends WXModule {
@WXModuleAnno(runOnUIThread = true)
public void printLog(String msg) {
Toast.makeText(mWXSDKInstance.getContext(),msg,Toast.LENGTH_SHORT).show();
}
}
JS 调用如下:
<template>
<div>
<text onclick="click">点击我测试</text>
</div>
</template>
<script>
module.exports = {
methods: {
click: function() {
require('@weex-module/myModule').printLog("我是一个测试!");
}
}
}
</script>
-keep public class * extends com.taobao.weex.ui.component.WXComponent{*;}
WXSDKEngine.registerComponent("richtext",RichText.class);
示例如下:
public class RichText extends WXComponent {
public RichText(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) {
super(instance, dom, parent, isLazy);
}
@Override
protected void initView() {
mHost=new TextView(mContext);
((TextView)mHost).setMovementMethod(LinkMovementMethod.getInstance());
}
@WXComponentProp(name = "tel")
public void setTelLink(String tel){
SpannableString spannable=new SpannableString(tel);
spannable.setSpan(new URLSpan("tel:"+tel),0,tel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
((TextView)mHost).setText(spannable);
}
}
JS 调用如下:
<template>
<div>
<richText tel="12305" style="width:200;height:100">12305</text>
</div>
</template>
图片下载:
需要时集成接口IWXImgLoaderAdapter,实现setImage 方法。
示例如下:
public class ImageAdapter implements IWXImgLoaderAdapter {
public ImageAdapter() {
}
@Override
public void setImage(final String url, final ImageView view,
WXImageQuality quality, WXImageStrategy strategy) {
WXSDKManager.getInstance().postOnUiThread(new Runnable() {
@Override
public void run() {
if(view==null||view.getLayoutParams()==null){
return;
}
if (TextUtils.isEmpty(url)) {
view.setImageBitmap(null);
return;
}
String temp = url;
if (url.startsWith("//")) {
temp = "http:" + url;
}
if (view.getLayoutParams().width <= 0 || view.getLayoutParams().height <= 0) {
return;
}
Picasso.with(WXEnvironment.getApplication())
.load(temp)
.into(view);
}
},0);
}
}
注:工程要添加依赖 compile 'com.squareup.picasso:picasso:2.5.2'