'Is there any reliable way to get the ViewGroup set by setContentView without using findViewById?

I create an Android Library in which it receives an Activity object as an input for initializing, during the initialization of my library, I want to get the ViewGroup set by Activity.setContentView, I've tried this way:

public void init(Activity activity) {
    ViewGroup tmp = activity.findViewById(android.R.id.content);
    ViewGroup currentVG = (ViewGroup) tmp.getChildAt(0);
}

It works, but I don't find any official documentation to confirm that, I suspect that It may work on my device or some specific Android version, but not for others, anyway I'm not sure.

  • Is there any official documentation for that?
  • Is it safe to use the way above to retrieve the ViewGroup without using findViewById? If not, Is there any reliable way?


Solution 1:[1]

When you call setContentView Android uses a LayoutInflater to inflate the resource and build the hierarchy of views for your Activity. So it's fine to use findViewById to get the root of the view. Not sure why you are calling getChildAt(0) on the content view. If you want the root of the content view you can call View#getRootView

You might want to add some error-handling in case the Activity was destroyed or never initialized (views are not valid and findViewById will return null.)

You'll also want to be careful not to hang on to any references to activities, or any other UI lifecycle objects, to avoid potential resource leaks.

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 zen_of_kermit