在Android应用程序中将React Native模块用作视图布局

时间:2018-07-17 03:39:59

标签: android react-native

我正在使用React Native,当我将React Native模块集成到android应用程序时遇到了一个问题。作为React Native指南页面,我们可以通过以下代码片段将RN模块添加到android中的Activity中:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mReactRootView = new ReactRootView(this);
    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("index.android.bundle")
            .setJSMainModulePath("index")
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    // The string here (e.g. "MyReactNativeApp") has to match
    // the string in AppRegistry.registerComponent() in index.js
    mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);

    setContentView(mReactRootView);
}

但是我只想将RN模块分配给规范视图:例如Frame Layout,这样我写了:

    public class PlaceholderContent extends FrameLayout {

        private Context mContext;
        private Application mApplication;


        public PlaceholderContent(@NonNull Context context, @NonNull Application application) {
            super(context);
            mContext = context;
            mApplication = application;
            init();
        }

        private void init() {
            ReactRootView contentView = new ReactRootView(mContext);
            ReactInstanceManager mReactInstanceManager;

            mReactInstanceManager = ReactInstanceManager.builder()
                    .setApplication(mApplication)
                    .setBundleAssetName("index.android.bundle")
                    .setJSMainModulePath("index")
                    .addPackage(new MainReactPackage())
                    .setUseDeveloperSupport(BuildConfig.DEBUG)
                    .setInitialLifecycleState(LifecycleState.RESUMED)
                    .build();

           contentView.startReactApplication(mReactInstanceManager, "MyReactApp", null);
           this.addView(contentView);
       //LayoutInflater.from(getContext()).inflate(R.layout.view_placeholder_content, this, true);

    //        RelativeLayout container = (RelativeLayout) findViewById(R.id.view_container);
    //        container.addView(contentView, -1, new RelativeLayout.LayoutParams(5000, 5000));
    //        LayoutInflater.from(getContext()).cloneInContext(contentView.getContext());
      }  }

我有两个问题:

  1. 首先,我上面的代码段是否正确?

  2. 如果正确,我将创建自己的组件(MyReactApp),但当应用运行时,屏幕显示它是默认的RN应用,如下图所示。那么,如何在android中正确显示我的RN视图?

screen when app running

谢谢大家,对我的E和我第一次来这里表示歉意。

0 个答案:

没有答案