In many of the code samples that I find on the internet the context
is obtained in the constructor of an adapter.
This context is used to get an inflater
to inflate the views in getView
method.
My Question is why bother getting the context in the constructor when it can easily be obtained like so
LayoutInflater inflater;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater == null){
Context context = parent.getContext();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
...
...
return convertView;
}
Also is there any reason not to use the above method because it till now I have not faced any problem in using it .
Obtaining the Context in the constructor has (at least) three advantages:
getView()
is called.parent
is null
.However, if you don't have any problems with your solution, you might as well stick to it.