使用react-native-splash-screen解决应用启动白屏问题

时间:2020-05-01

使用react-native-splash-screen库

文档:https://www.npmjs.com/package/react-native-splash-screen

安装

npm i react-native-splash-screen --save
react-native link react-native-splash-screenreact-native link react-native-splash-screen

修改MainActivity.java文件

android\app\src\main\java\com\wyzda\MainActivity.java

import android.os.Bundle;
import org.devio.rn.splashscreen.SplashScreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
    SplashScreen.show(this);
    super.onCreate(savedInstanceState);
}

完整代码

package com.wyzda;

import com.facebook.react.ReactActivity;
import android.os.Bundle;
import org.devio.rn.splashscreen.SplashScreen;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "wyzda";
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    SplashScreen.show(this);
    super.onCreate(savedInstanceState);
  }
}

在app/src/main/res/layout目录下创建launch_screen.xml文件,目录不存在则手动创建!

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical" android:layout_width="match_parent"
                android:layout_height="match_parent">
    <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:src="@mipmap/launch_screen" android:scaleType="centerCrop" />
</RelativeLayout>

把你的启动图重命名为launch_screen.png并放到android\app\src\main\res\mipmap-hdpi

请参考安卓启动图片存放位置!

新建文件:android\app\src\main\res\values\colors.xml 目录不存在则手动创建

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary_dark">#000000</color>
</resources>

修改 android\app\src\main\res\values\styles.xml 文件

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:textColor">#000000</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>

</resources>

在你的应用首页使用,下面是3秒后关闭启动图的使用方法。

引用库

import SplashScreen from 'react-native-splash-screen';

在组件加载后3秒后隐藏

componentDidMount() {
    setTimeout(() => {
         SplashScreen.hide();
    },3000);
}