Java – Can ListView have two or more different types of row layouts in Android?

Can ListView have two or more different types of row layouts in Android?… here is a solution to the problem.

Can ListView have two or more different types of row layouts in Android?

I now have a very simple ListView in a ListActivity that only displays a list of text values. Here is my current code :

public class InfoActivity extends ListActivity {

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

List<String> values = new ArrayList<String>();
         loads up the values array here
        // ...

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android. R.layout.simple_list_item_1, values);
        setListAdapter(adapter);
    }

I

don’t have anything in the InfoActivity XML file because I’m using a ListActivity.

What I want to do is create a custom layout for the rows. The first 5 rows will contain layoutA.xml, and the last 5 lines will contain layoutB.xml.

What should I do? I don’t know where to start. Obviously, I’m looking for code that is as simple as possible.

Solution

It’s simple, you just need to extend the ArrayAdapter. My ArrayAdapter does two different things:

  • My adapter takes a set of ResourceIds instead of passing a single ResourceId
  • getView() checks the location and loads the appropriate resources

This is a simple example. If you intend to make it seem more complicated than the first half, and the second half is different, then you should cover it getViewTypeCount() and getItemViewType() .

Working example:

public class Example extends Activity {
    public class MyArrayAdapter<T> extends ArrayAdapter<T> {
        LayoutInflater mInflater;
        int[] mLayoutResourceIds;

public MyArrayAdapter(Context context, int[] textViewResourceId, List<T> objects) {
            super(context, textViewResourceId[0], objects);
            mInflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
            mLayoutResourceIds = textViewResourceId;
        }

@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null && position > 2)
                convertView = mInflater.inflate(mLayoutResourceIds[1], parent, false);
            return super.getView(position, convertView, parent);
        }
    }

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

String[] array = new String[] {"one", "two", "three", "four", "five", "six"};
        List<String> list = new ArrayList<String>();
        Collections.addAll(list, array);

ListView listView = new ListView(this);
        listView.setAdapter(new MyArrayAdapter<String>(this, new int[] {android. R.layout.simple_list_item_1, android. R.layout.simple_list_item_single_choice}, list));
        setContentView(listView);
    }
}

Related Problems and Solutions