findViewById(android.R.id.statusBarBackground) ret

2019-04-17 09:58发布

问题:

I'm trying to get StatusBarView (I need it for activity shared element transition animation).

I use the following code in my activity:

View decorView = getWindow().getDecorView();
View statusBar = decorView.findViewById(android.R.id.statusBarBackground);

But statusBar is always null. I tried this code after onCreate() and after onResume() - no effect.

What's wrong?

回答1:

Snippet for those who just need a clean answer without reading the whole topic linked by T.Vert

    final View decor = getWindow().getDecorView();
    decor.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            decor.getViewTreeObserver().removeOnPreDrawListener(this);
            View statusBar = decor.findViewById(android.R.id.statusBarBackground);
            return true;
        }
    });