【发布时间】:2010-08-05 15:35:34
【问题描述】:
我的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 上是 TextViews。但是,txtLabel1 和 txtLabel2 在尝试设置它们后为空。为什么?
我在调试器中单步执行了这段代码,它膨胀了正确的布局 (R.layout.layout_A) 并落入下面的正确大小写以设置 R.id.label1 和 R.id.label2 文本。
另外,如果有更好的方法,请告诉我。
【问题讨论】:
-
检查this tutorial。他们解释了与您要实现的目标类似的内容。