Question

I would like to know why sometime getActivity.findViewById() works and sometimes it returns null ?

And with myView.findViewById() it works ?

Thanks in advance :)

Was it helpful?

Solution

findViewById is not a global search for a View. It only looks in specific places. If no View is specified (as in your myView.findViewById() example) findViewById will look in the content view for the Activity or Fragment you are calling it from. Otherwise it will look within the specified view.

You will get null if you are looking for the view in the wrong place - i.e. what you are looking for is not in the place you're searching.

Here's an example: if you're using a ListView whose items you are controling with an Adapter you would need to call findViewbById on the inflated layout for the indivdual items in order to set their child views. Why? Because a ListView starts out empty. If you called findViewById within the general ListActivity you would be looking for list item fields in the wrong place, i.e. the content view for the activity - not the layout that will eventually be inflated for each list item.

OTHER TIPS

I'm supposing you are in a Fragment and calling getActivity.findViewById().

Looking at the source code, Activity.findViewById() call findViewById() on the Window which calls findViewById() on its decor view.

So when you call getActivity.findViewById() you're searching for a subview of your decor view.

If you call findViewById() directly on a view, you're looking for a subview from the given View.

So if view is not in your decor view subviews, getActivity.findViewById() will return null while view.findViewById() will works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top