I have a ListView
on my ListActivity
and I'd like the rows of the ListView
to be 1 of 3 different layouts. The first item in my list is always going to use layout A, the second item in my list is always going to use layout B, and all subsequent items are going to use layout C.
Here is my getView function:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// get the View for this list item
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
switch (position) {
case 0:
v = vi.inflate(R.layout.layout_A, parent, false);
break;
case 1:
v = vi.inflate(R.layout.layout_B, parent, false);
break;
default:
v = vi.inflate(R.layout.layout_C, parent, false);
break;
}
}
switch (position) {
case 0:
TextView txtLabel1 = (TextView)findViewById(R.id.label1);
TextView txtLabel2 = (TextView)findViewById(R.id.label2);
if (txtLabel1 != null) {
txtLabel1.setText("sdfasd");
}
if (txtLabel2 != null) {
txtLabel2.setText("dasgfadsasd");
}
break;
default:
break;
}
// return the created view
return v;
}
R.id.label1
and R.id.label2
are TextViews
on R.layout.layout_A
. However, txtLabel1
and txtLabel2
are null after trying to set them. Why?
I stepped through this code in the debugger and it inflated the correct layout (R.layout.layout_A
) and fell into the correct case below to set the R.id.label1
and R.id.label2
text.
Also, if there is a better way to do this, please let me know.
Yes its possible. You can use as many layouts as possible for a single activity but obviously not simultaneously.
Try this: my_listview. setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } });
Looks like "View v = convertView; if (v == null) {..." is a problem. You should re-create view every time because you don't know the type of given view. Also, you can use viewholder approach for more efficient implementation. You can find some ideas in this blog: http://codinglines.frankiv.me/post/18486197303/android-multiple-layouts-in-dynamically-loading
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