日知其所亡,月勿忘其所能,可谓学也已矣。
很久前测试过。但是今天又温故下,发现好多细节有所遗忘,(忘性还真大)还是记录下吧。
调用原生Toast模块。
1.创建ToastModule Java类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import android.widget.Toast;
import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod;
import java.util.HashMap; import java.util.Map;
public class ToastModule extends ReactContextBaseJavaModule {
private static final String DURATION_SHORT_KEY = "SHORT"; private static final String DURATION_LONG_KEY = "LONG";
public ToastModule(ReactApplicationContext reactContext) { super(reactContext); }
@Override public String getName() { return "MyToastAndroid"; }
@Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT); constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG); return constants; }
@ReactMethod public void show(String message, int duration) { Toast.makeText(getReactApplicationContext(), message, duration).show(); }
}
|
2.注册模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class ToastPackage 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 ToastModule(reactContext));
return modules; }
|
3.在MainApplication.java中添加你自己定义的
new ToastPackage()
4.为了方便调用,可以在创建ToastAndroid.js 作为专门的模块,
1 2 3 4 5
| import { NativeModules } from 'react-native';
export default NativeModules.MyToastAndroid;
|
5.index.android.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableWithoutFeedback } from 'react-native';
import ToastAndroid from './ToastAndroid';
class MyDemo extends Component { render() { return ( <View > <TouchableWithoutFeedback onPress={() => ToastAndroid.show('show toast', ToastAndroid.SHORT)}> <Text style={styles.text}>Click me.</Text> </TouchableWithoutFeedback> </View> ); } }
const styles = StyleSheet.create({
text: { color: 'black', }, });
AppRegistry.registerComponent('MyDemo', () => MyDemo);</span>
|