| 版权声明:本文为博主原创文章,未经博主允许不得转载。
一、简介
上篇文章介绍到功能组件的封装,JS端和Native端之间的通讯相对来讲还是很简单的,今天我们介绍封装UI组件以及JS端和Native之间的通信方式。
1. 创建CustomImageView类
// 创建自定义View
public static class CustomImageView extends View {
public CustomImageView(Context context) {
super(context);
// TODO 可做一些初始化工作
}
public CustomImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
2. 创建ViewManager的子类
- 继承ReactNative封装的SimpleViewManager类,或者继承ViewManager类;
public class UIComponentViewManager extends SimpleViewManager<UIComponentViewManager.CustomImageView> {
private static final String REACT_CLASS = "RCTImageView";
@Override
public String getName() {
return REACT_CLASS;
}
}
3. 实现createViewInstance方法
public class UIComponentViewManager extends SimpleViewManager<UIComponentViewManager.CustomImageView> {
private static final String REACT_CLASS = "RCTImageView";
private CustomImageView mCustomImageView;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected CustomImageView createViewInstance(ThemedReactContext reactContext) {
// 初始化自定义视图类
mCustomImageView = new CustomImageView(reactContext);
return mCustomImageView;
}
}
4. 暴露出设置视图属性的Setter方法,使用@ReactProp或者@ReactPropGroup声明
public class UIComponentViewManager extends SimpleViewManager<UIComponentViewManager.CustomImageView> {
private static final String REACT_CLASS = "RCTImageView";
private CustomImageView mCustomImageView;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected CustomImageView createViewInstance(ThemedReactContext reactContext) {
mCustomImageView = new CustomImageView(reactContext);