Android 具有多项目布局的列表视图
我的Android 具有多项目布局的列表视图,android,listview,layout,Android,Listview,Layout,我的ListActivity上有一个ListView,我希望ListView的行是三种不同布局中的一种。我的列表中的第一项总是使用布局A,列表中的第二项总是使用布局B,所有后续项都将使用布局C 下面是我的getView函数: @Override public View getView(int position, View convertView, ViewGroup parent) { // get the View for this list item View v = co
ListActivity
上有一个ListView
,我希望ListView
的行是三种不同布局中的一种。我的列表中的第一项总是使用布局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
上的文本视图
。但是,txtLabel1
和txtLabel2
在尝试设置后为空。为什么?
我在调试器中逐步检查了这段代码,它膨胀了正确的布局(R.layout.layou A
),并进入下面的正确案例中,以设置R.id.label1
和R.id.label2
文本
另外,如果有更好的方法,请告诉我。看起来像“查看v=convertView;如果(v==null){…”这是一个问题。您应该每次都重新创建视图,因为您不知道给定视图的类型。此外,您可以使用viewholder方法来更有效地实现。您可以在本博客中找到一些想法:这是一个非常糟糕的主意,会显著降低性能。Macarse postet是一个很好的示例,它将尝试重用视图不管怎样。检查一下。他们解释了一些与你想要达到的目标相似的东西。