Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Listview with different layout for each row?

I want to create Listview in which I want different layout for all different row. Then how can I create custom adapter for set different layout for different row.

Any help would be greatly appreciated.

Thank you in Advance.

like image 478
Arvind Kanjariya Avatar asked Nov 01 '13 08:11

Arvind Kanjariya


2 Answers

You need to extend your Adapter, and override its getView method.

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

    int resource;

    // Here you set ‘resource’ with the correct layout, for the row
    // given by the parameter ‘position.’
    //
    // E.g.:
    //
    // switch (someArray[position].type) {
    //   case SOME_TYPE_A: resource = R.layout.a; break;
    //   case SOME_TYPE_B: resource = R.layout.b; break;
    //   ...
    // }

    View rowView = inflater.inflate(resource, parent, false);

    // Here you initialize the contents of the newly created view.
    //
    // E.g.:
    // switch (resource) {
    //   case R.layout.a:
    //      TextView aA = (TextView) rowView.findViewById(R.id.aa);
    //      aA.setText("View 1");
    //      ...
    //      break;
    //   case R.layout.b:
    //      TextView bB = (TextView) rowView.findViewById(R.id.bb);
    //      bB.setText("View 2");
    //      ...
    //      break;
    //   ...
    // }

    return rowView;
}

For more examples on adapters and how to extend them, see the links below.

  • http://www.vogella.com/articles/AndroidListView/article.html#adapterown

  • http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

like image 142
André Kugland Avatar answered Oct 22 '22 01:10

André Kugland


create regular adapter , in the create_view function inflate the row xml layout according to the row type.

for example

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

     if (position % 2 == 0 )
        xml_type = R.layout.row_one
     else
         xml_type = R.layout.row_two

     View rowView = inflater.inflate(xml_type, parent, false);
}
like image 28
Jow Avatar answered Oct 22 '22 00:10

Jow