问题
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