您现在的位置是:首页 >技术交流 >React Native的fragment和JetPack ViewPager2的集成网站首页技术交流

React Native的fragment和JetPack ViewPager2的集成

北极象 2024-07-09 12:01:02
简介React Native的fragment和JetPack ViewPager2的集成

背景

ViewPager2是ViewPager的升级版,在原生Android应用中使用广泛。近期本人项目需要添加一些React Native页面,怎么在现有的ViewPager2中添加Fragment,然后在Fragment里显示RN的页面?经过试验,发现其实也比较容易做。但目前google上几乎没搜到例子,于是分享一下。

原生ViewPage2的代码结构

Main Activity的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.MainActivity"
    android:orientation="vertical">


    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/design_default_color_primary_dark"
        app:tabIconTint="@color/grey"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/white"
        app:tabTextColor="@color/grey" />

</LinearLayout>

ViewPager对应的Adapter类:

package com.icool.cms.android.adapter

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.facebook.react.ReactFragment
import com.icool.cms.android.R
import com.icool.cms.android.model.Category
import com.icool.cms.android.ui.*

public class HomePagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    private val TAG = "HomePagerAdapter"
    override fun getItemCount(): Int {
        return 4
    }

    override fun createFragment(position: Int): Fragment {
        lateinit var fragment: Fragment
        when (position) {
            0 -> {
                fragment = ArticleHomeFragment()
            }
            1 -> {
                fragment = SysEventFragment()                
            }
            2 -> {
                fragment = MessagingHomeFragment()                
            }
            3 -> {
                fragment = MeHomeFragment()
            }
        }
        Log.i(TAG, "Created CMS Fragment successfully.")
        return fragment

    }  
}

React Native端的实现

假如我们要在ViewPager2中添加两个Fragment,每个对应一个RN组件,则需要先注册两个RN组件:

import {AppRegistry} from 'react-native';
import Component1 from './component1';
import Component2 from './component2';

AppRegistry.registerComponent('component1', () => Component1);
AppRegistry.registerComponent('component2', () => Component2);

原生端的实现

在Adapter中注册Fragment

import com.facebook.react.ReactFragment
...
 override fun getItemCount(): Int {
        return 6
 }
    
override fun createFragment(position: Int): Fragment {
        lateinit var fragment: Fragment
        when (position) {
            0 -> {
                fragment = ArticleHomeFragment()
            }
            1 -> {
                fragment = SysEventFragment()                
            }
            2 -> {
                fragment = MessagingHomeFragment()                
            }
            3 -> {
                fragment = MeHomeFragment()
            }
            4 -> {
                fragment = ReactFragment()
                val args = Bundle()
                args.putString("arg_component_name", "component1")
                fragment.arguments = args
            }
            5 -> {
                fragment = ReactFragment()
                val args = Bundle()
                args.putString("arg_component_name", "component2")
                fragment.arguments = args
            }
        }
        Log.i(TAG, "Created CMS Fragment successfully.")
        return fragment

MainActivity实现DefaultHardwareBackBtnHandler接口

class MainActivity : AppCompatActivity(), DefaultHardwareBackBtnHandler {
	...
	   override fun invokeDefaultOnBackPressed() {
        	TODO("Not yet implemented")
    	}
	}
}

小结

RN和原生应用的集成,既可以以Activity的形式,也可以以Fragment的形式,有了两者融合方式后,底座采用kotlin,上层采用RN,即可满足性能和功能的需求,实现快速开发迭代。

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。