日知其所亡,月勿忘其所能,可谓学也已矣。
很久前测试过。但是今天又温故下,发现好多细节有所遗忘,(忘性还真大)还是记录下吧。
调用原生Toast模块。
1.创建ToastModule Java类。
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 getConstants() {
final Map 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.注册模块
class ToastPackage implements ReactPackage {
@Override
public List> createJSModules() {
return Collections.emptyList();
}
@Override
public List createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List createNativeModules(
ReactApplicationContext reactContext) {
List modules = new ArrayList<>();
modules.add(new ToastModule(reactContext));
return modules;
}
3.在MainApplication.java中添加你自己定义的
new ToastPackage()
4.为了方便调用,可以在创建ToastAndroid.js 作为专门的模块,
import { NativeModules } from 'react-native';
export default NativeModules.MyToastAndroid;
5.index.android.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableWithoutFeedback
} from 'react-native';
import ToastAndroid from './ToastAndroid';
class MyDemo extends Component {
render() {
return (
ToastAndroid.show('show toast', ToastAndroid.SHORT)}>
Click me.
);
}
}
const styles = StyleSheet.create({
text: {
color: 'black',
},
});
AppRegistry.registerComponent('MyDemo', () => MyDemo);