react-native加载Fragment与加载一般的view一样
1、创建布局文件layout_react_native_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fl_react_native_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
2、创建rn view
public class FragmentViewManager extends SimpleViewManager<View> {
private final String TAG = "react-native-fragment";
private final String REACT_FRAGMENT_VIEW = "BaseReactNativeFragment";
private final int COMMAND_TEST_FRAGMENT = 100;
@Nonnull
@Override
public String getName() {
return REACT_FRAGMENT_VIEW;
}
@Nonnull
@Override
protected View createViewInstance(@Nonnull ThemedReactContext reactContext) {
this.mContext = reactContext;
ReactNativeLinearLayout root = (ReactNativeLinearLayout) LayoutInflater.from(reactContext).inflate(R.layout.layout_react_native_fragment,null);
return root;
}
@Nullable
@Override
public Map<String, Integer> getCommandsMap() {
HashMap<String,Integer> commandsMap = new HashMap<>();
commandsMap.put("creatTestFragment",COMMAND_TEST_FRAGMENT );
return commandsMap;
}
@Override
public void receiveCommand(@Nonnull View root, int commandId, @Nullable ReadableArray args) {
Logger.t(TAG).d("commandId="+commandId);
switch (commandId){
case COMMAND_TEST_FRAGMENT :
createTestFragment();
break;
}
}
private ThemedReactContext mContext;
private void createTestFragment(){
TestFragment testFragment = new TestFragment();
if(mContext != null){
Activity activity = mContext.getCurrentActivity();
FragmentManager fragmentManager = ((AppCompatActivity)activity).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fl_react_native_container, testFragment ).commitNowAllowingStateLoss();
}
}
}
PS:要注册添加到RN中与RN调用原生View一样
3、NativeFragment.tsx
import React, { Component } from "react";
import { requireNativeComponent, UIManager, findNodeHandle } from "react-native";
const NativeFragment = requireNativeComponent('BaseReactNativeFragment')//与原生中 FragmentViewManager中的getName 一致
class NativeFragmentextends Component {
fragment = null;
componentDidMount(){
this.timer = setTimeout(()=>{
this.fragment.createTestTab ();
},500);
}
render() {
return (
<NativeFragment ref={c => this.fragment = c} {...this.props} style={{ flex: 1 }} />
)
}
createTestTab =()=>{
UIManager.dispatchViewManagerCommand(
findNodeHandle(this.fragment),
UIManager.getViewManagerConfig("BaseReactNativeFragment").Commands.creatTestFragment,//获取原生中FragmentViewManager getCommandsMap 参数,传递到receiveCommand方法中
[] //参数
)
}
}
export default NativeFragment
这样就可以直接跟其他view一样调用,在componentDidMount中延迟500毫秒,如果不延迟 fragmentTransaction.add 页面会无法展示出来。
网友评论