与 Android Fragment 集成
与现有应用集成 的指南详细介绍了如何将全屏 React Native 应用作为 Activity 集成到现有的 Android 应用中。要在现有应用的 Fragment 中使用 React Native 组件,需要进行一些额外的设置。这样做的好处是,它允许原生应用将 React Native 组件与 Activity 中的原生片段集成在一起。
¥The guide for Integration with Existing Apps details how to integrate a full-screen React Native app into an existing Android app as an Activity. To use React Native components within Fragments in an existing app requires some additional setup. The benefit of this is that it allows for a native app to integrate React Native components alongside native fragments in an Activity.
1. 将 React Native 添加到你的应用
¥ Add React Native to your app
按照 与现有应用集成 的指南进行操作,直到代码集成部分。继续执行步骤 1。创建 index.android.js
文件和步骤 2。从本部分添加你的 React Native 代码。
¥Follow the guide for Integration with Existing Apps until the Code integration section. Continue to follow Step 1. Create an index.android.js
file and Step 2. Add your React Native code from this section.
2. 将你的应用与 React Native 片段集成
¥ Integrating your App with a React Native Fragment
你可以将 React Native 组件渲染为 Fragment,而不是全屏 React Native Activity。该组件可能被称为 "screen" 或 "fragment",其功能与 Android 片段相同,可能包含子组件。这些组件可以放置在 /fragments
文件夹中,用于组成片段的子组件可以放置在 /components
文件夹中。
¥You can render your React Native component into a Fragment instead of a full screen React Native Activity. The component may be termed a "screen" or "fragment" and it will function in the same manner as an Android fragment, likely containing child components. These components can be placed in a /fragments
folder and the child components used to compose the fragment can be placed in a /components
folder.
你需要在主应用 Java/Kotlin 类中实现 ReactApplication
接口。如果你从 Android Studio 创建了一个具有默认活动的新项目,则需要创建一个新类(例如 MyReactApplication.java
或 MyReactApplication.kt
)。如果它是现有的类,你可以在 AndroidManifest.xml
文件中找到该主类。在 <application />
标签下,你应该看到属性 android:name
,例如 android:name=".MyReactApplication"
。该值是你想要实现并提供所需方法的类。
¥You will need to implement the ReactApplication
interface in your main Application Java/Kotlin class. If you have created a new project from Android Studio with a default activity, you will need to create a new class (e.g. MyReactApplication.java
or MyReactApplication.kt
). If it is an existing class you can find this main class in your AndroidManifest.xml
file. Under the <application />
tag you should see a property android:name
e.g. android:name=".MyReactApplication"
. This value is the class you want to implement and provide the required methods to.
确保你的主应用类实现了 ReactApplication:
¥Ensure your main Application class implements ReactApplication:
- Java
- Kotlin
class MyReactApplication: Application(), ReactApplication {...}
public class MyReactApplication extends Application implements ReactApplication {...}
覆盖所需的方法 getUseDeveloperSupport
、getPackages
和 getReactNativeHost
:
¥Override the required methods getUseDeveloperSupport
, getPackages
and getReactNativeHost
:
- Java
- Kotlin
class MyReactApplication : Application(), ReactApplication {
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
}
private val reactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getUseDeveloperSupport() = BuildConfig.DEBUG
override fun getPackages(): List<ReactPackage> {
val packages = PackageList(this).getPackages().toMutableList()
// Packages that cannot be autolinked yet can be added manually here
return packages
}
}
override fun getReactNativeHost(): ReactNativeHost = reactNativeHost
}
public class MyReactApplication extends Application implements ReactApplication {
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, false);
}
private final ReactNativeHost mReactNativeHost = new DefaultReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here
return packages;
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
如果你使用的是 Android Studio,请使用 Alt + Enter 添加类中所有缺少的导入。或者,这些是需要手动包含的导入:
¥If you are using Android Studio, use Alt + Enter to add all missing imports in your class. Alternatively these are the required imports to include manually:
- Java
- Kotlin
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.soloader.SoLoader
import android.app.Application;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.soloader.SoLoader;
import java.util.List;
执行 "与 Gradle 同步项目文件" 操作。
¥Perform a "Sync Project files with Gradle" operation.
步骤 3。为 React Native Fragment 添加 FrameLayout
¥Step 3. Add a FrameLayout for the React Native Fragment
现在,你将把 React Native Fragment 添加到 Activity 中。对于新项目,此 Activity 将为 MainActivity
,但它可以是任何 Activity,并且当你将更多 React Native 组件集成到应用中时,可以将更多片段添加到其他 Activity。
¥You will now add your React Native Fragment to an Activity. For a new project this Activity will be MainActivity
but it could be any Activity and more fragments can be added to additional Activities as you integrate more React Native components into your app.
首先将 React Native Fragment 添加到你的 Activity 布局中。例如 main_activity.xml
位于 res/layouts
文件夹中。
¥First add the React Native Fragment to your Activity's layout. For example main_activity.xml
in the res/layouts
folder.
添加带有 id、宽度和高度的 <FrameLayout>
。这是你将找到的布局并将你的 React Native Fragment 渲染到其中。
¥Add a <FrameLayout>
with an id, width and height. This is the layout you will find and render your React Native Fragment into.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/reactNativeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
步骤 4。将 React Native 片段添加到 FrameLayout
¥Step 4. Add a React Native Fragment to the FrameLayout
要将 React Native Fragment 添加到布局中,你需要有一个 Activity。正如新项目中提到的,这将是 MainActivity
。在此活动中添加一个按钮和一个事件监听器。单击按钮后,你将渲染 React Native 片段。
¥To add your React Native Fragment to your layout you need to have an Activity. As mentioned in a new project this will be MainActivity
. In this Activity add a button and an event listener. On button click you will render your React Native Fragment.
修改你的活动布局以添加按钮:
¥Modify your Activity layout to add the button:
<Button
android:layout_margin="10dp"
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show react fragment" />
现在,在你的 Activity 类(例如 MainActivity.java
或 MainActivity.kt
)中,你需要为按钮添加 OnClickListener
,实例化 ReactFragment
并将其添加到框架布局中。
¥Now in your Activity class (e.g. MainActivity.java
or MainActivity.kt
) you need to add an OnClickListener
for the button, instantiate your ReactFragment
and add it to the frame layout.
将按钮字段添加到活动的顶部:
¥Add the button field to the top of your Activity:
- Java
- Kotlin
private lateinit var button: Button
private Button mButton;
更新你的 Activity 的 onCreate
方法,如下所示:
¥Update your Activity's onCreate
method as follows:
- Java
- Kotlin
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val reactNativeFragment = ReactFragment.Builder()
.setComponentName("HelloWorld")
.setLaunchOptions(getLaunchOptions("test message"))
.build()
getSupportFragmentManager()
.beginTransaction()
.add(R.id.reactNativeFragment, reactNativeFragment)
.commit()
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mButton = findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment reactNativeFragment = new ReactFragment.Builder()
.setComponentName("HelloWorld")
.setLaunchOptions(getLaunchOptions("test message"))
.build();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.reactNativeFragment, reactNativeFragment)
.commit();
}
});
}
在上面的代码中,Fragment reactNativeFragment = new ReactFragment.Builder()
创建了 ReactFragment,getSupportFragmentManager().beginTransaction().add()
将 Fragment 添加到了 Frame Layout。
¥In the code above Fragment reactNativeFragment = new ReactFragment.Builder()
creates the ReactFragment and getSupportFragmentManager().beginTransaction().add()
adds the Fragment to the Frame Layout.
如果你使用的是 React Native 入门套件,请将 "HelloWorld" 字符串替换为 index.js
或 index.android.js
文件中的字符串(它是 AppRegistry.registerComponent() 方法的第一个参数)。
¥If you are using a starter kit for React Native, replace the "HelloWorld" string with the one in your index.js
or index.android.js
file (it’s the first argument to the AppRegistry.registerComponent() method).
添加 getLaunchOptions
方法,该方法将允许你将 props 传递到你的组件。这是可选的,如果不需要传递任何属性,可以删除 setLaunchOptions
。
¥Add the getLaunchOptions
method which will allow you to pass props through to your component. This is optional and you can remove setLaunchOptions
if you don't need to pass any props.
- Java
- Kotlin
private fun getLaunchOptions(message: String) = Bundle().apply {
putString("message", message)
}
private Bundle getLaunchOptions(String message) {
Bundle initialProperties = new Bundle();
initialProperties.putString("message", message);
return initialProperties;
}
在你的 Activity 类中添加所有缺少的导入。请小心使用你的包的 BuildConfig,而不是 facebook 包中的 BuildConfig!或者,这些是需要手动包含的导入:
¥Add all missing imports in your Activity class. Be careful to use your package’s BuildConfig and not the one from the facebook package! Alternatively these are the required imports to include manually:
- Java
- Kotlin
import android.app.Application
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.shell.MainReactPackage
import com.facebook.soloader.SoLoader
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
执行 "与 Gradle 同步项目文件" 操作。
¥Perform a "Sync Project files with Gradle" operation.
步骤 5。测试你的集成
¥Step 5. Test your integration
确保运行 yarn
来安装 React-native 依赖,并运行 yarn native
来启动 Metro 打包程序。在 Android Studio 中运行你的 Android 应用,它应该从开发服务器加载 JavaScript 代码并将其显示在 Activity 中的 React Native Fragment 中。
¥Make sure you run yarn
to install your react-native dependencies and run yarn native
to start the metro bundler. Run your android app in Android Studio and it should load the JavaScript code from the development server and display it in your React Native Fragment in the Activity.
步骤 6。附加设置 - 原生模块
¥Step 6. Additional setup - Native modules
你可能需要从 React 组件调用现有的 Java/Kotlin 代码。原生模块允许你调用原生代码并在原生应用中运行方法。按照此处的设置进行操作 native-modules-android
¥You may need to call out to existing Java/Kotlin code from your react component. Native modules allow you to call out to native code and run methods in your native app. Follow the setup here native-modules-android