GrowinMan GrowinMan - 1 year ago 46
Android Question

How does the getView() method work when creating your own custom adapter?

My questions are:

  1. What is exactly the function of the LayoutInflater?

  2. Why do all the articles that I've read check if convertview is null or not first? What does it mean when it is null and what does it mean when it isn't?

  3. What is the parent parameter that this method accepts?

Answer Source

1: The LayoutInflater takes your layout XML-files and creates different View-objects from its contents.

2: The adapters are built to reuse Views, when a View is scrolled so that is no longer visible, it can be used for one of the new Views appearing. This reused View is the convertView. If this is null it means that there is no recycled View and we have to create a new one, otherwise we should use it to avoid creating a new.

3: The parent is provided so you can inflate your view into that for proper layout parameters.

All these together can be used to effectively create the view that will appear in your list (or other view that takes an adapter):

public View getView (int position, View convertView, ViewGroup parent){
    if( convertView == null ){
        //We must create a View:
        convertView = inflater.inflate(R.layout.my_list_item, parent, false);
    //Here we can do changes to the convertView, such as set a text on a TextView 
    //or an image on an ImageView.
    return convertView;

Notice the use of the LayoutInflater, that parent can be used as an argument for it, and how convertView is reused.