Android listview中项目的不同布局

Android listview中项目的不同布局,android,listview,cursor,adapter,Android,Listview,Cursor,Adapter,我有一些扩展的游标适配器,在其中我使用上下文和列表中项目的资源布局调用super,类似这样 在我的适配器中调用super: super(activity, viewResource, c, false); new MyCursorAdapter(this, null, R.layout.my_list_item, null); 创建我的适配器: super(activity, viewResource, c, false); new MyCursorAdapter(this, null,

我有一些扩展的游标适配器,在其中我使用上下文和列表中项目的资源布局调用super,类似这样

在我的适配器中调用super:

super(activity, viewResource, c, false);
new MyCursorAdapter(this, null, R.layout.my_list_item, null);
创建我的适配器:

super(activity, viewResource, c, false);
new MyCursorAdapter(this, null, R.layout.my_list_item, null);
我想要达到的是我用油漆做的愚蠢的模型。 换言之,我希望对项目有不同类型的布局,例如,我希望所有偶数项目都有布局1,所有奇数项目都有布局2。到目前为止,在本例中,我只能给出一个布局R.layout.my_list_项。是否可以动态更改布局? 是否可以将适配器构造为具有不同布局的项?我的目标是动态选择项目的布局。我不想只有一个布局的所有项目,我想有一个例子二

谢谢


是的,不过你必须做两件事。首先,覆盖适配器中的
getItemViewType()
方法,以便确保
bindView()
仅获取适合列表中特定位置的视图,如下所示:

public int getItemViewType(int position){
  if(correspondsToViewType1(position)){
    return VIEW_TYPE_1;
  }
  else(correspondsToViewType2(position)){
    return VIEW_TYPE_2;
  }
  //and so on and so forth.
}
完成此操作后,只需在
bindView()
中进行一个简单测试,检查应该接收的视图类型,并相应地设置如下内容:

public void bindView(View view, Context context, Cursor cursor){
  if(correspondsToViewType1(cursor)){
    //Now we know view is of a particular type and we can do the 
    //setup for it
  }
  else if(correspondsToViewType2(cursor){
    //Now we know view is of a different type and we can do the 
    //setup for it
  }
}
请注意,对于correpondsToViewType,您必须使用不同的方法,一个使用光标,另一个使用int(表示位置)。这些操作的实现将根据您想要执行的操作而有所不同


请注意,这样做将允许您重用可能回收的视图。如果你不这样做,你的应用程序将受到巨大的性能打击。滚动将非常频繁。

我猜您是从自定义适配器的名称扩展而来的。您需要覆盖适配器中的功能,并根据列表中的对象为不同的布局充气并返回该视图

例:


这只是一个示例,有点像sudo代码,因此需要根据您的具体情况进行一些调整。

只需覆盖newView方法:

public class MyCursorAdapter extends CursorAdapter {

private final LayoutInflater inflater;
    private ContentType type;

public MyCursorAdapter (Context context, Cursor c) {
    super(context, c);
    inflater = LayoutInflater.from(context);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    if( cursor.getString(cursor.getColumnIndex("type")).equals("type1") ) {
                // get elements for type1
    } else {
                // get elements for type1
            }

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    if( cursor.getString(cursor.getColumnIndex("type")).equals("type1") ) {
        final View view = inflater.inflate(R.layout.item_type1, parent, false);
    } else {
        final View view = inflater.inflate(R.layout.item_type2, parent, false);
    }
    return view;
}

这行不通。他正在扩展已经覆盖getView方法的CursorAdapter。您不想弄乱这个方法,因为它做了一些特殊的事情,包括获取适当的游标。再加上他得到的视图可能不是正确的类型,因此他将永远无法使用它,他的应用程序将受到巨大的性能冲击。@Kurtis Nusbaum的方法看起来更加可靠。我建议使用他的一个。这是不好的,因为它不允许他使用在bindView中传递的视图参数,该参数可能已经被回收。他每次都必须创建一个新的视图,因此他的应用程序的性能将受到巨大的冲击。对不起,马克,在我添加了我的应用程序后,请发表你的评论。非常感谢。不过我会在这里留下我的评论作为解释。谢谢,我总是很高兴学习;)这只是我看到你的代码之前的第一个想法。