How to implement a React Native UI component method in Android

匆匆过客 提交于 2019-12-04 10:10:27

Ok I ended up creating a Module, and passing a UI Component reference on it's constructor:

Here's my UI component:

public class RCTACCalendarManager extends ViewGroupManager <RCTACCalendar> {
    public static final String REACT_CLASS = "RCTACCalendar";
    private RCTACCalendar calendarInstance;
    public RCTACCalendarManager(ReactApplicationContext reactContext) {
            super();
        }

        @Override
        public String getName() {
            return REACT_CLASS;
        }


        @Override
        public RCTACCalendar createViewInstance(ThemedReactContext context) {
            calendarInstance = new RCTACCalendar(context);
            return calendarInstance;
    }

    public RCTACCalendar getCalendarInstance() { // <-- returns the View instance
        return calendarInstance;
    }

}

Here's the Module I created for that component:

public class RCTACCalendarModule extends ReactContextBaseJavaModule {

    private RCTACCalendar calendarInstance;

    public RCTACCalendarModule(ReactApplicationContext reactContext, RCTACCalendarManager calManager) {
        super(reactContext);
        if (calManager != null) {
            calendarInstance = calManager.getCalendarInstance();
        }

    }

    @Override
    public String getName() {
        return "ACCalendarManager";
    }

    @ReactMethod
    public void mySuperDuperFunction(Promise promise) {
        if (calendarInstance  != null) {
            calendarInstance.mySuperDuperFunction(promise); // <-- Magic
        }
    }
}

and here's how I combine those two together in my Package declaration:

public class RCTACCalendarPackage implements ReactPackage {

    private RCTACCalendarManager calManager;

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        if (calManager == null) {
            calManager = new RCTACCalendarManager(reactContext);
        }
        return Arrays.<NativeModule>asList(
                new RCTACCalendarModule(reactContext, calManager)
        );

    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        if (calManager == null) {
            calManager = new RCTACCalendarManager(reactContext);
        }
        return Arrays.<ViewManager>asList(
            calManager
        );
    }
}

It works like a charm.

For react-native Android UI Component, you have to make your view class extends SimpleViewManager.

See document here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!