參數類型java
Boolean -> Bool
Integer -> Number
Double -> Number
Float -> Number
String -> String
Callback -> function
ReadableMap -> Object
ReadableArray -> Array
複製代碼
1.在MainApplication
添加你的package react
1.在MainApplication添加你的package ide
2.在package中添加你的ViewManager 3.在你的ViewManager中添加給RN掉用的屬性 4.添加java代碼public class GradualButton extends FrameLayout implements LifecycleEventListener {
protected ThemedReactContext mContext;
private TextView mGradualButton;
private boolean mDisabled;
public GradualButton(@NonNull ThemedReactContext context) {
super(context);
init(context);
}
public GradualButton(@NonNull ThemedReactContext context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public GradualButton(@NonNull ThemedReactContext context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public void init(ThemedReactContext context) {
mContext = context;
mContext.addLifecycleEventListener(this);
mGradualButton = new TextView(context);
mGradualButton.setGravity(Gravity.CENTER);
mGradualButton.setTextColor(Color.WHITE);
mGradualButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
setPadding(0, 0, 0, 0);
addView(mGradualButton);
initListener();
}
protected void initListener() {
mGradualButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mDisabled) {
sendMessageToRn("onClick", null);
}
}
});
mGradualButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (!mDisabled) {
sendMessageToRn("onLongClick", null);
}
return false;
}
});
}
public void setWidth(int width) {
int resultWidth = Dp2Px(getContext(), width);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mGradualButton.getLayoutParams();
layoutParams.width = resultWidth;
mGradualButton.setLayoutParams(layoutParams);
}
public void setHeight(int height) {
int resultHeight = Dp2Px(getContext(), height);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mGradualButton.getLayoutParams();
layoutParams.height = resultHeight;
mGradualButton.setLayoutParams(layoutParams);
}
public void setText(String text) {
mGradualButton.setText(text);
}
public void setDisable(boolean disabled) {
mDisabled = disabled;
mGradualButton.setClickable(!disabled);
}
/** * 回調RN的事件 * * @param eventName 事件名稱 * @param data 攜帶數據 */
public void sendMessageToRn(String eventName, WritableMap data) {
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),//native層和js層兩個視圖會依據getId()而關聯在一塊兒
eventName,//事件名稱
data//事件攜帶的數據
);
}
public int Dp2Px(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
@Override
public void onHostResume() {
}
@Override
public void onHostPause() {
}
@Override
public void onHostDestroy() {
}
}
複製代碼
5.在RN中使用this
原生提供給RN調用的名稱,也就是getName()方法的返回值,最好單獨放一個文件,便於管理spa