Tengo ListView
en mi y me gustaría que las filas de ListView
sean 1 de 3 diseños diferentes. El primer elemento de mi lista siempre va a usar el diseño A, el segundo elemento de mi lista siempre usará el diseño B, y todos los elementos posteriores van a usar el diseño C.ListViews con varios diseños de elementos
Aquí está mi función getView:
@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
R.id.label2
y son TextViews
en R.layout.layout_A
. Sin embargo, txtLabel1
y txtLabel2
son nulos después de intentar establecerlos. ¿Por qué?
Pasé por este código en el depurador e infló el diseño correcto (R.layout.layout_A
) y caí en el caso correcto a continuación para establecer el R.id.label1
y R.id.label2
de texto.
Además, si hay una mejor manera de hacerlo, házmelo saber.
Consulte [este tutorial] (http://android.amberfog.com/?p=296). Explican algo similar con lo que estás tratando de lograr. – Macarse