【问题标题】:Not able to set headers in a Listview using a SimpleAdapter in Android无法在 Android 中使用 SimpleAdapter 在 Listview 中设置标题
【发布时间】:2014-09-11 05:44:56
【问题描述】:

我正在尝试使用SimpleAdapter 对我的ListView 项目进行分组。我正在使用两个 Layouts r1 和 r2。我已经完成了以下编码,但我只得到了我的 ListView 中显示的布局 r2 的内容。谁能指导我哪里出错了?我的代码如下:

 adapter=new SimpleAdapter(MainActivity.this, arraylist,R.layout.r1,new String[]{"key1","key2"},new int[]{R.id.textView1,R.id.textView2})
    {



        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View v=super.getView(position, convertView, parent);

            LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(MainActivity.this.LAYOUT_INFLATER_SERVICE);
                int type = getItemViewType(position);
                Log.i("position + convertview + type ",""+position+","+convertView+","+type);
                if(convertView==null)
                {

                     v = inflater.inflate(R.layout.r2, parent, false);
                }
                else
                {
                     v = inflater.inflate(R.layout.r1, parent, false);
                }



                return v;

        }

    };

    l.setAdapter(adapter);

【问题讨论】:

标签: android listview header simpleadapter


【解决方案1】:

getView

 if (type == FIRST_TYPE) {
       //infalte layout of type1
 }else if( type == SECOND_TYPE){
      //infalte layout of type2
 }

您的类型对应。

private static final int FIRST_TYPE= 0;
private static final int SECOND_TYPE = 1;

你可以有基于位置的标题。

@Override
public int getItemViewType(int position) {

    if (position== 0){
        type = FIRST_TYPE;
    } else if  (position == 1){
        type = SECOND_TYPE;
    }
    return type;
}

你也可以使用 commonsware 合并适配器

https://github.com/commonsguy/cwac-merge

【讨论】:

  • 这里的FIRST_TYPE和SECOND_TYPE是什么?
  • @Ann 0 对应标题,1 对应内容。由你来修改
  • 我无法覆盖 getItemViewType
  • @Ann 使用 ArrayAdapter 或 BaseAdapter
【解决方案2】:

判断条件错误

convertView 为空。

你可以搜索android ListView resusing views 例如ListView reusing views when ... I don't want it to

所以如果要使用两种布局,请使用其他判断条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多