列表视图中项目的不同布局

时间:2011-10-20 14:18:51

标签: android listview cursor adapter

我有一些扩展的游标适配器,我用上下文和列表中项目的资源布局调用super,就像这样。

在我的适配器中调用super:

super(activity, viewResource, c, false);

创建我的适配器:

new MyCursorAdapter(this, null, R.layout.my_list_item, null);

我想要实现的就像我在画中制作的愚蠢模拟。 单词我希望项目有不同的布局,例如我希望所有偶数项都有layout1,所有奇数都有layout2。到目前为止,我只能在这种情况下给出一个布局R.layout.my_list_item。是否可以动态更改布局? 是否可以构造适配器以使项目具有不同的布局?我的目标是动态选择项目的布局。我不想只为我想要的所有项目设置一个布局,例如两个......

由于

enter image description here

3 个答案:

答案 0 :(得分:2)

是的,你将不得不做两件事。首先,覆盖适配器中的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(一个位置)。这些的实现取决于您想要做什么。

请注意,以这种方式执行操作将允许您重用可能已回收的视图。如果您不这样做,您的应用将会受到巨大性能影响。滚动会非常不稳定。

答案 1 :(得分:0)

我猜你从自定义适配器的名称扩展SimpleCursorAdapter。您将希望覆盖适配器中的函数getView,并根据列表中的对象膨胀不同的布局并返回该视图。

EX:

     @Override
     public View getView (int position, View convertView, ViewGroup parent)
     {
            Object myObject = myList.get(position);

            if(convertView == null)
            {
                  if( something to determine layout )
                        convertView = inflater.inflate(Layout File);
                  else
                        convertView = inflater.inflate(Some Other Layout File);
            }

            //Set up the view here, such as setting textview text and such

            return convertView;
     }

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

答案 2 :(得分:0)

只需覆盖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;
}