React native 沉浸式状态栏解决方案

前端之家收集整理的这篇文章主要介绍了React native 沉浸式状态栏解决方案前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

React native 沉浸式状态栏解决方

博客上有很多的沉浸式解决方案,不过都是针对原生activity的方案。在react native中却不适用。
首先我们看一下RN中的StatusBar中的属性
translucent bool :指定状态栏是否透明。设置为true时,应用会在状态栏之下绘制(即所谓“沉浸式”——被状态栏遮住一部分)。常和带有半透明背景色的状态栏搭配使用。
js中调用的是setTranslucent(bool)
源码如下:` @ReactMethod
public void setTranslucent(final boolean translucent) {
final Activity activity = getCurrentActivity();
if (activity == null) {
FLog.w(ReactConstants.TAG,“StatusBarModule: Ignored status bar change,current activity is null.”);
return;
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  UiThreadUtil.runOnUiThread(
    new GuardedRunnable(getReactApplicationContext()) {
      @TargetApi(Build.VERSION_CODES.LOLLIPOP)
      @Override
      public void runGuarded() {
        // If the status bar is translucent hook into the window insets calculations
        // and consume all the top insets so no padding will be added under the status bar.
        View decorView = activity.getWindow().getDecorView();
        if (translucent) {
          decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @Override
            public WindowInsets onApplyWindowInsets(View v,WindowInsets insets) {
              WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
              return defaultInsets.replaceSystemWindowInsets(
                defaultInsets.getSystemWindowInsetLeft(),defaultInsets.getSystemWindowInsetRight(),defaultInsets.getSystemWindowInsetBottom());
            }
          });
        } else {
          decorView.setOnApplyWindowInsetsListener(null);
        }

        ViewCompat.requestApplyInsets(decorView);
      }
    });
}

}`
所以我的做法就是参考源码:

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = this.getWindow().getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsets onApplyWindowInsets(View v,WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),0,defaultInsets.getSystemWindowInsetRight(),defaultInsets.getSystemWindowInsetBottom());
                }

            });
            ViewCompat.requestApplyInsets(decorView);
        }

    }

在js代码其实可以直接调用setTranslucent,但是后来在项目中发现,Android sdk 6.0以上,打成release包会出现问题,首次进入app的时候都会出现,状态栏没有设置成功。然后再次进入项目,就会成功,所以我仿照源码动态的来设置。 但是这个是没有改变状态栏背景色,如果你需要改变背景色,也可以参考设置背景色的源码来设置。

猜你在找的React相关文章