Android Listview with a different layout for each row?

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

Any help would be greatly appreciated.

Thank you at Advance.

+7
android android-layout
source share
2 answers

You need to extend the 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.' // // Eg: // // 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. // // Eg: // 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; } 

See below for additional examples of adapters and how to expand them.

+8
source share

create a regular adapter; in the create_view function, inflate the xml layout according to the type of string.

eg

 @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); } 
+6
source share

All Articles