NULL оконные вставки - PullRequest
       41

NULL оконные вставки

0 голосов
/ 02 декабря 2018

Я пытаюсь получить DisplayCutout и получаю

java.lang.NullPointerException: попытка вызвать виртуальный метод 'android.view.DisplayCutout android.view.WindowInsets.getDisplayCutout ()' нанулевая ссылка на объект

Вот мой код:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
   DisplayCutout displayCutout;
   displayCutout = getWindow().getDecorView().getRootWindowInsets().getDisplayCutout();
   //Logger.e(TAG, "MARGIN " + displayCutout.getSafeInsetTop());
}

Ответы [ 6 ]

0 голосов
/ 02 августа 2019
public static boolean hasNotchInScreenOfAndroidP(View context) {
    final boolean[] ret = {false};
    final View view=context;
    if (Build.VERSION.SDK_INT >= 28) {
        if (context==null){
        }else {
            context.post(new Runnable() {
                @Override
                public void run() {
                    WindowInsets windowInsets=view.getRootWindowInsets();
                    if (windowInsets==null){
                    }else {
                        DisplayCutout displayCutout = view.getRootWindowInsets().getDisplayCutout();
                        if (displayCutout == null ) {
                            ret[0] = false;
                        } else {
                            List<Rect> rects = displayCutout.getBoundingRects();
                            if (rects == null || rects.size() == 0) {
                                ret[0] = false;
                            } else {
                                ret[0] = true;
                            }
                        }
                    }
                }
            });

        }

    }
    return ret[0];
}

ComUtil.getStateBarHeightOfSeparationFromTheTop (this, getWindow (). GetDecorView ());

0 голосов
/ 17 июля 2019

Это происходило у меня при запуске эмулятора.Похоже, даже если у вас есть эмулятор со скином по умолчанию, который имеет вырез экрана, он все равно может не зарегистрировать его в качестве устройства отключения дисплея.

Вы можете обойти это, включив опцию «Имитация дисплея с вырезом» в параметрах разработчика:
https://developer.android.com/guide/topics/display-cutout/#test_how_your_content_renders

0 голосов
/ 05 июня 2019

Вы должны поставить свой код на

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
      DisplayCutout displayCutout;
      displayCutout = 
      getWindow().getDecorView().getRootWindowInsets().getDisplayCutout();
     //Logger.e(TAG, "MARGIN " + displayCutout.getSafeInsetTop());
    }
}
0 голосов
/ 12 апреля 2019

вы можете получить DisplayCutout в обработчике

    val cutoutHandler = HandlerThread("cutout-thread")
    cutoutHandler.start()
    var handler = object : Handler(cutoutHandler.looper) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            runOnUiThread {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { // 9.0原生
                    val windowInsets = window.decorView.rootWindowInsets
                    val displayCutout = windowInsets.displayCutout
                }
                cutoutHandler.quit()
            }
        }
    }
    Thread {
        handler.sendEmptyMessage(0)
    }.start()
0 голосов
/ 14 февраля 2019

попробуйте код ниже.Мне удалось получить высоту строки состояния с помощью View.OnAttachStateChangeListener .В моем случае я подключил прослушиватель к ScrollView (mDetailScrollView), измените его на любое представление, к которому вы хотите присоединить прослушиватель.

    ...
    mDetailScrollView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
        @Override
        public void onViewAttachedToWindow(View v) {                
            DisplayCutout displayCutout = getDisplayCutout();
            if (displayCutout != null) {
                // your code...
            }
        }

        @Override
        public void onViewDetachedFromWindow(View v) {
        }
    });
    ...

    private DisplayCutout getDisplayCutout() {
        if (activity != null) {
            WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
            if (windowInsets != null) {
                return windowInsets.getDisplayCutout();
            }
        }

        return null;
    }
0 голосов
/ 02 декабря 2018

getRootWindowInsets возвращает ноль, если и только если представление отключено.Убедитесь, что вы звоните из правильного контекста.

...