문제

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

And with myView.findViewById() it works ?

Thanks in advance :)

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top