Search code examples
androidbaseadapterlayout-inflater

Why does the base parameter give an error in the layout inflator?


I am creating a custom BaseAdapter class,

public class CustomAdapter extends BaseAdapter {

    Context c;
    ArrayList<String> items;

    CustomAdapter(Context c,ArrayList<String> items)
    {

        this.c=c;
        this.items=items;

    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        View v= view;
        TextView tv;
        LayoutInflater layoutInflater = (LayoutInflater)c
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        ViewHolder pattern;

        if(view==null)
        {

            v = layoutInflater.inflate(R.layout.dummy,viewGroup,true);



            tv = (TextView)v.findViewById(R.id.textView);

            pattern = new ViewHolder(v);
            v.setTag(pattern);
        }
        else{
            pattern = (ViewHolder)v.getTag();
            return v;
        }

        pattern.tv.setText(items.get(i));



        return v;
    }
}

I get this error,

addView(View, LayoutParams) is not supported in AdapterView

It is because I am passing a true in this code,

v = layoutInflater.inflate(R.layout.dummy,viewGroup,true);

My Question is why is there an error when we pass true here ? Doesn't BaseAdapter accept it ?


Solution

  • The boolean parameter in the inflate method determines if the created view should be added to the ViewGroup you provided as second parameter. doc

    Since your 2nd parameter is an AdapterView, Android will try to add the view directly to the AdapterView. But AdapterView doesn't suppport the addView() method ref

    You are not supposed to add the view directly to the ViewGroup in the getView() method. Just return it and you should be fine.