2

I have a listView that is being populated by ArrayAdapter. I want a different layout for first Row/Cell of the ListView.

Also I found a very similar question but cldnt add headerView in my code Android different Row layout only for first row in BaseAdapter

I have implemented that using the code below:

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource1;
int Resource2;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource1 = resource;
    Resource2 = resource;
    actorList = objects;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;

    if (v == null) {
        holder = new ViewHolder();
        if (position == 0){
            v = vi.inflate(R.layout.first_item, null);
            holder.imageview = (ImageView) v.findViewById(R.id.thumb);
            holder.tvName = (TextView) v.findViewById(R.id.title);

        }
        else{
            v = vi.inflate(R.layout.list_item, null);
            holder.imageview = (ImageView) v.findViewById(R.id.thumb);
            holder.tvName = (TextView) v.findViewById(R.id.title);

        }

        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.ic_launcher);
    Picasso.with(getContext()).load(actorList.get(position).getImage()).into(holder.imageview);
    String postTitle = actorList.get(position).getName();
    Spanned deTitle = Html.fromHtml(Html.fromHtml((String) postTitle).toString());
    holder.tvName.setText(String.valueOf(deTitle));

    return v;

}

The problem is, My list initially fetches 10 items. After that I load More articles as the user scrolls down. Now the 11th item of the list also gets layout of 1st item.

Also, when i scroll back to the top, the layout of first item is changed to that of other list items.

Please help with this.

Community
  • 1
  • 1
Swapna Lekshmanan
  • 514
  • 10
  • 30

2 Answers2

6

Override getViewTypeCount() in your adapter to return 2. Override getItemViewType() to return 0 for position 0 and return 1 for all other positions. This teaches the ListView that you have two different row layouts, where the first row (position 0) has a different layout than do the other rows. This will ensure that row recycling gives you back the correct row layout for your position.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

Add these two methods in your ActorAdapter class:

@Override
public int getViewTypeCount() {
    return getCount();
}

@Override
public int getItemViewType(int position) {
    return position;
}
Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
Rahul Sharma
  • 5,949
  • 5
  • 36
  • 46