Android Fragments getView returns parent of view?

So I came across some odd behavior when it comes to the getVIew () method in the fragment class. From the documentation, I expect to get the view created in the onCreateView method, as indicated here http://developer.android.com/reference/android/app/Fragment.html#getView ()

"Get the root view for the fragment layout (the one returned by onCreateView (LayoutInflater, ViewGroup, Bundle)), if provided"

Now I have a view in which there are many children, so I wanted to try and save when I try to findViewById by implementing the ViewHolder class, similar to the usual way that it does in the ListView adapters that I set as the view tag returned from onCreateView.

Odd behavior occurs later when I call the getView method. It appears that the fragment returns the parent of the created view, not the created view, which results in the return of the null tag.

I wrote a small price for the code to print the view (nested children if the view is actually a viewGroup), and this is what I get.

android.widget.ScrollView android.widget.ScrollView@4242dec0 /android.widget.ScrollView 

and when I print it later using the getView () method, I get

  android.support.v4.app.NoSaveStateFrameLayout android.widget.ScrollView android.widget.ScrollView@4242dec0 /android.widget.ScrollView /android.support.v4.app.NoSaveStateFrameLayout 

As you can see, ScrollView is the view that I actually create in the onCreateView method. So why does getView return the parent instead of the view?

+4
source share
2 answers

The support library inserts an additional view into the view hierarchy. According to a comment in NoSaveStateFrameLayout.java: "There is no View.setSaveFromParentEnabled () on Pre-Honeycomb versions of the platform, so instead we insert this between the view and its parent."

So, you need to either check this for something like:

 View myView = (NoSaveStateFrameLayout)getView(); if (myView != null) { myView = myView.getChildAt(0); } 

Or track the view returned by onCreateView in an instance variable.

+1
source

Could it be that you create an adapter before completing onCreateView ? I had a problem when I had a function calling getView () and manipulating layout elements before returning onCreateView, which led to a misconception. I ended up sending a bloated view from onCreateView to a function, and it worked just fine.

0
source

All Articles