As you know, for inflating a view, we need context to get LayoutInflater
.I have seen many tutorials that pass context as an argument to PagerAdapter
to solve this problem. I recently have found that we can access context from instantiateItem
like below:
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
Context context = container.getContext();
...
}
but I wonder whether it is best practice or not?
Yes, totally fine. A ViewGroup
is a View
and getContext()
will return you a Context
to which the view is attached to, ie it's the outbound Activity
. This is the context that you want to use for accessing layouts and resources while rendering adapter items.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.