I have a very simple ListView right now in a ListActivity that displays just a list of text values. Here's 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);
}
My XML file for InfoActivity has nothing in it because I am using a ListActivity.
What I want to do it make custom layouts for the rows. The first 5 rows will have layoutA.xml and the second 5 rows will have layoutB.xml.
How do I do this? I'm lost on where to begin. Obviously I'm looking for the simplest code possible.
This is easy enough, you simply need to extends ArrayAdapter. My ArrayAdapter does two things differently:
This is a trivial example. If you plan on making it more complex than the first half looks one way and the second half is different, then you should override 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With