Search code examples
androidlistviewandroid-listviewandroid-custom-viewbaseadapter

How to customize listview to have different layouts for first and second position of row items?


I am working on a project where i need to customize the listview with different layouts for each row item as follows
(i) First position in a row item should be a normal imageview and textview
(ii) Second position in a row item should be a horizontal listview
(iii) Third position in a row itme should be a normal custom listview

I know all of these things to do separately but i dont know how to proceed to merge into a single listview by only changing the row items position. The image of my exact requirement is enter image description here .
Also i am sharing you some piece of code for custom listview adapter class for your reference

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;

    String[] country;
      int[] flag;
    LayoutInflater inflater;

    public ListViewAdapter(Context context, String[] country, int[] flag) {
        this.context = context;
        this.country = country;
        this.flag = flag;
    }

    @Override
    public int getCount() {
        return country.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

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

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

        // Declare Variables
        TextView txtcountry;
        ImageView imgflag;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);

        // Locate the TextViews in listview_item.xml
        txtcountry = (TextView) itemView.findViewById(R.id.country);
        // Locate the ImageView in listview_item.xml
        imgflag = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set to the TextViews
        txtcountry.setText(country[position]);

        // Capture position and set to the ImageView
        imgflag.setImageResource(flag[position]);

        return itemView;
    } <br>

Please help me to achieve this. Thanks in advance


Solution

  • You can inflate each row with different view in the adapter. Use:

    public View getView(int position, View convertView, ViewGroup parent) {
    if(position==0)
    {
    //view 1
    }
    
    else if(position==1)
    {
    //View 2
    }
    
    else
    {
    Rest of the list elements
    }