Why to use Inflater in listview

user2609157 picture user2609157 · Aug 2, 2013 · Viewed 30.5k times · Source
  • I always had ambiguity on why we need to use inflater in android, Why are they used in ListView for custom layouts (like below)?
  • What is an Inflater ?
  • What is the advantage of using Inflater ?

public class MobileArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;


public MobileArrayAdapter(Context context, String[] values) {
    super(context, R.layout.list_mobile, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_mobile, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
    textView.setText(values[position]);

Thanks,

Answer

Joel picture Joel · Aug 2, 2013

What is an Inflater ?

To summarize what the LayoutInflater Documentation says... A LayoutInflater is one of the Android System Services that is responsible for taking your XML files that define a layout, and converting them into View objects. The OS then uses these view objects to draw the screen.

I always had ambiguity on why we need to use inflater in android, Why are they used in android ListView for a custom layout ?

Typically, you don't ever need to directly use a LayoutInflater. Android does most of the layout inflation for you when you call setContentView() in the onCreate() method of your activity. So you, as the programmer, are responsible for making sure the views are inflated. Now you want to inflate views in the context of a ListView. The Adapter class can do the inflation for you if you do not want to customize each item. But if you want to customize the views shown in a list, you will have to manually inflate each view with the LayoutInflater, since there is no other existing method you can use.

What is the advantage of using Inflater ?

There is no advantage to using it. You are required to use a LayoutInflater in some shape or form to inflate your static XML layouts.

Alternatively, you could create views dynamically with java code. However, you would need to call methods to set each property for the view by hand. In my opinion, it is easier to use the XML/inflation process. In addition, Android pre-processes your XML files at build time, so this results in a faster execution time.