react native 开发原生 Android 组件

React native开发原生Android组件

此处的例子是在天气APP demo里,为了实现下雨效果,在原生实现的动画View
天气APP的github地址:
https://github.com/gehaiqing/react-native-weather

JAVA层自定义View

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.reactweather;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
public class AnimateView extends ViewGroup {
private final float scale = this.getResources().getDisplayMetrics().density;
private int repeatCount = Animation.INFINITE;
private int delay = 0;
private float translateY = 0;
private int duration = 0;
public AnimateView(Context context) {
super(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
//设置延时
public void setDelay(int delay){
this.delay = delay;
}
//设置Y方向位移
public void setTranslateY(float y){
this.translateY = (int) (y*this.scale + 0.5);
}
//设置持续时间
public void setDur(int time){
this.duration = time;
}
//开始动画
public void start(){
TranslateAnimation transAnim = new TranslateAnimation(0, 0, 0, this.translateY);
transAnim.setDuration(this.duration);
transAnim.setStartOffset(this.delay);
transAnim.setRepeatCount(this.repeatCount);
this.clearAnimation();
this.startAnimation(transAnim);
System.out.println("start " + this.getContext().getPackageCodePath());
}
@Override
protected void onAttachedToWindow(){
System.out.println("attach to window");
}
}

JAVA层自定义ViewManager

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.reactweather;
import android.widget.Toast;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.Map;
public class AnimateViewManager extends ViewGroupManager<AnimateView> {
public static final int COMMAND_START = 1;
// React-Native官方大多数自定义View都是用RCT开头,这里保持规范性
private static final String REACT_CLASS = "RCTAnimateView";
//JS中使用的组件名称
@Override
public String getName() {
// 此处name在后面JS组件开发时会用到,需要统一命名
return REACT_CLASS;
}
//重写方法,创建实例
@Override
protected AnimateView createViewInstance(ThemedReactContext reactContext) {
// AnimateView实例
return new AnimateView(reactContext);
}
//与JS映射。 属性 dur
@ReactProp(name = "dur", customType = "int")
public void setDur(AnimateView view, int dur ){
view.setDur(dur);
}
//与js映射。 属性 delay
@ReactProp(name = "delay", customType = "int")
public void setDelay(AnimateView view, int delay ){
view.setDelay(delay);
}
//与js映射。 属性 translateY
@ReactProp(name = "translateY", customType = "float")
public void setMoveY(AnimateView view, float translateY ){
view.setTranslateY(translateY);
}
//从react继承
//返回命令序列
//JS根据返回的命令列表,向Native发送命令,Native根据接受到的命令处理,如方法调用
@Override
public Map<String, Integer> getCommandsMap() {
System.out.println("getcommandsmap");
return MapBuilder.of(
"start",
COMMAND_START
);
}
//接受由js发送过来的命令
@Override
public void receiveCommand(AnimateView view, int commandId, ReadableArray args) {
String msg = "recieve command " + commandId;
System.out.println(msg);
switch (commandId) {
case COMMAND_START: {
view.start();
}
}
}
}

JAVA层注册ViewManager

在MainApplication.java中的getPackages函数中添加新的react packge, 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new ReactPackage() {//添加新的react package
@Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(new AnimateViewManager());
}
@Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
}
);
}

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @providesModule RCTGradientColorView
* 自定义native UI组件
*/
'use strict';
import React, { Component, PropTypes } from 'react';
import {
View,
requireNativeComponent,
findNodeHandle,
UIManager,
Platform
} from 'react-native';
class AnimateView extends Component {
shouldComponentUpdate(nextProps) {
return false;
}
/**
* 开始动画
* 通过`dispatchViewManagerCommand`调用自定义组件中的方法
* `UIManager.RCTAnimateView.Commands`.start 是在JAVA层中定义的
* `RCTAnimateView` 为JAVA层中定义的名称
* @memberOf AnimateView
*/
start() {
UIManager.dispatchViewManagerCommand(findNodeHandle(this), UIManager.RCTAnimateView.Commands.start,
[Platform.OS === 'android' ? JSON.stringify(this.data || []) : null]);
}
/**
* 组件更新后
* 由于`redux`原因,需延迟500ms开始动画
*
* @memberOf AnimateView
*/
componentDidUpdate() {
this.timer = setTimeout(() => {
this.start();
}, 500)
}
/**
* 由于redux原因,需延迟500ms开始动画
*
* @memberOf AnimateView
*/
componentDidMount() {
this.timer = setTimeout(() => {
this.start();
}, 500)
}
/**
* 组件卸载时清除未开始的定时器
*
* @memberOf AnimateView
*/
componentWillUnmount(){
clearTimeout(this.timer);
}
render() {
return (
<NativeAnimateView
{...this.props}>
{this.props.children}
</NativeAnimateView>
);
}
};
// 与Java层AnimateView中@ReactProp注解的方法参数保持一致
/**
* 配置propTypes
*/
AnimateView.propTypes = {
delay: PropTypes.number,
dur: PropTypes.number,
translateY: PropTypes.number,
...View.propTypes //这个必须要有
}
//通过组件名称加载原生的Android组件
//第一个参数是原生组件的名称
//第二个参数描述组件接口的对象,需包含propTypes属性,用于描述接口
var NativeAnimateView = requireNativeComponent('RCTAnimateView', AnimateView);
module.exports = AnimateView;

使用JS自定义组件

1
2
3
4
5
import AnimateView from '../native-components/AnimateView';
<AnimateView dur={item.dur} delay={item.delay} translateY={item.translateY} key={index} style={[{ position: 'absolute', top: item.top, left: item.left }]}>
<Text style={[styles.snow, { top: 0, left: 0, width: item.size, height: item.size,fontSize:item.size }]}>&#xe610;</Text>
</AnimateView>

参考:http://blog.csdn.net/MegatronKings/article/details/50959518

本文地址: http://gehaiqing.com/blog/2017/02/22/20170222-react-native-android-native-component/