Call methods from the Activity class (React Native Android)

不打扰是莪最后的温柔 提交于 2020-02-02 05:18:49

问题


Is there an api to call methods from the Activity class? I need to call finish() on my app but couldn't find anything relevant in the docs.

To be more specific, I want to finish() the MainActivity from my index.android.jsx, when a particular TouchableHighlight is pressed.

[update]

For now I'm exposing a finish() method from my NativeModule but maybe there's a better way to do that.

https://github.com/sneerteam/react-native-sneer/blob/master/src/main/java/me/sneer/react/SneerModule.java#L84


回答1:


I don't see a built in way to do this either and your approach using NativeModule is what I use as well.

However, if you call setCurrentActivity when building your ReactInstanceManager then you can call getCurrentActivity from your module instead of passing it through the ReactPackage and ReactModule constructors.

MyReactModule.java

public class MyReactModule extends ReactContextBaseJavaModule {

    public MyReactModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return getClass().getSimpleName();
    }

    @ReactMethod
    public void finish() {
        Activity activity = getCurrentActivity();
        if (activity != null) {
            activity.finish();
        }
    }

}

MyReactPackage.java

public class MyReactPackage implements ReactPackage {

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new MyReactModule(reactContext));
        return modules;
    }

}

ReactInstanceManager Setup

mReactInstanceManager = ReactInstanceManager.builder()
        .addPackage(new MyReactPackage())
        .setCurrentActivity(this)
        // other settings
        .build();


来源:https://stackoverflow.com/questions/33352553/call-methods-from-the-activity-class-react-native-android

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