首页 > 解决方案 > 如何为 React Native App 提供 Android 缺口支持

问题描述

我想让我的应用程序的窗口在缺口的两侧绘制。我遵循了这篇文章的指南,并在我的res文件夹中创建了values-v28文件夹。之后,我在 values-v28 文件夹中创建了 styles.xml 并添加了以下代码

<style name="ActivityTheme">
    <item name="android:windowLayoutInDisplayCutoutMode">
        shortEdges
    </item>
</style>

但是我的应用程序的窗口仍然总是被绘制在缺口之下。我完全困惑什么是正确的方法来做到这一点。

标签: androidreact-nativereact-native-android

解决方案


我设法让它工作!

我写了这篇文章来解释这些步骤。

这是一个 TL/DR:

  1. 将这些行添加到您的MainActivity.java
public class MainActivity extends ReactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
+            layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
+            getWindow().setAttributes(layoutParams);
+            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
+            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
+        }

        super.onCreate(savedInstanceState);
    }
  1. 然后安装并链接react-native-safe-area-context以处理缺口填充。这是最终结果:

在此处输入图像描述

代码:

import React from 'react'
import { StatusBar, Text, View } from 'react-native'
import { useSafeArea } from 'react-native-safe-area-context'

export function App() {
  const safeAreaInsets = useSafeArea()

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: '#ffca28',
        paddingTop: safeAreaInsets.top,
        paddingBottom: safeAreaInsets.bottom,
        paddingLeft: safeAreaInsets.left,
        paddingRight: safeAreaInsets.right,
      }}
    >
      <StatusBar backgroundColor="#7cb342" />

      <Text style={{ color: 'black', textAlign: 'center' }}>Top</Text>
      <View
        style={{
          flex: 1,
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <Text style={{ color: 'black', textAlign: 'center' }}>Left</Text>
        <Text style={{ color: 'black', textAlign: 'center' }}>Right</Text>
      </View>
      <Text style={{ color: 'black', textAlign: 'center' }}>Bottom</Text>
    </View>
  )
}

推荐阅读