On Android 7, getting context of a DecorView
returns a DecorContext
class and it's not an Activity. I used to get activity using Activity a = (Activity)view.getContext()
but it's not working for DecorView on Android 7 anymore. Is there any efficient way to get activity from a DecorView?
I'm using reflection to get the window of DecorView, and then get the context of that window (which is an Acitivity) for now.
Field f = decorView.getClass().getDeclaredField("mWindow");
f.setAccessible(true);
Window w = (Window) f.get(decorView);
Activity a = (Activity) w.getContext();
Is there any way that uses standard API?
In Android 7 (Nougat) Android introduced the multi-window feature, enabling you to open 2 activities at once on the screen (whether it's your activities or 2 different ones). To do that they introduced a new class called DecorContext
to be used by the DecorView
. The DecorContext
is (quote) "Context for decor views which can be seeded with pure application context and not depend on the activity, but still provide some of the facilities that Activity has, e.g. themes, activity-based resources, etc.". This means that the DecorView
no longer knows to which Activity
it's related to, only to which Application
. Hence going forward from Nougat, one cannot get the Activity
from the DecorView
alone.
Not sure if it's still relevant to you, but you can do this:
Activity a = (Activity) decorView.findViewById(android.R.id.content).getContext();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With