Reputation: 276
So I have encountered some odd behaviour when it comes to the getVIew() method in the fragment class. From the documentation I am expecting to get the view created in the onCreateView method as is stated here http://developer.android.com/reference/android/app/Fragment.html#getView()
"Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided"
Now, I have a view that has in it a fair number of children so I wanted to try and save when i try and "findViewById" by implementing a ViewHolder class similar to the common way it is done in ListView Adapters which I set to be the tag of the view returned from the onCreateView.
The odd behaviour occurs later when I call the getView method. It appears that the fragment is returning the parent of the view I create rather than the view I create which results in a null tag being returned.
I wrote a small price of code to print out a view (nesting the 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 the ScrollView is the view I actually create in the onCreateView method. So why is getView returning the parent instead of the view?
Upvotes: 4
Views: 2391
Reputation: 809
The support library inserts an additional view into the view hierarchy. According to a comment in NoSaveStateFrameLayout.java: "Pre-Honeycomb versions of the platform don't have View.setSaveFromParentEnabled(), so instead we insert this between the view and its parent."
So you will need to either check for this with something like:
View myView = (NoSaveStateFrameLayout)getView();
if (myView != null) {
myView = myView.getChildAt(0);
}
Or keep track of the view returned by onCreateView in an instance variable.
Upvotes: 1
Reputation: 2266
Could it be that you are creating the Adapter before onCreateView
completes? I had an issue where I had a function calling getView() and manipulating the the layout elements before onCreateView returned, causing the incorrect view to be used. I ended up sending the inflated view from onCreateView to the function, and it worked worked out fine.
Upvotes: 0