我在ListActivity上有一个ListView,我希望ListView的行是3种不同的布局中的一种.我的列表中的第一个项目总是使用布局A,列表中的第二个项目总是使用布局B,所有后续项目都将使用布局C.
这是我的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是R.layout.layout_A上的TextView.但是,txtLabel1和txtLabel2尝试设置后为空.为什么?
我在调试器中浏览了这个代码,并且它膨胀了正确的布局(R.layout.layout_A),并在下面的正确的例子中设置了R.id.label1和R.id.label2文本.
另外,如果有更好的方式来做,请让我知道.