'Trouble getting systemBars Insets on Android 11+

I'm fairly new to Android, and I've been experimenting with edge-to-edge content as described in this guide just making it work with a basic RecyclerView that scrolls behind a transparent navigation bar. As the guide instructs, I use window insets to adjust padding and prevent overlap:

ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.layout_root), (v, windowInsets) -> {
            Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
            Log.d("DEBUG", "Insets: " + insets.toString());
            v.setPadding(0, insets.top, 0, insets.bottom);
            return WindowInsetsCompat.CONSUMED;
        });

Everything works perfectly on Android 10, but the top inset always returns 0 when testing on Android 11 or 12. So far I've found a lot about changes to Window Insets in Android 11, but I can't find anything pertaining to this particular issue.



Solution 1:[1]

I faced the same issue as well. It always returned 0.

I fixed my issue with the following:

int insetTypes = WindowInsetsCompat.Type.displayCutout() | WindowInsetsCompat.Type.systemBars();
Insets insets = windowInsets.getInsets(insetTypes);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric Cen