在listview中使用两个布局

时间:2014-03-18 19:06:48

标签: android android-layout android-listview baseadapter

我需要在列表视图中使用两种不同的布局。第一个位置应使用R.layout.profile_element_one,而其余位置使用R.layout.profile_element_two。我试图在R.layout.profile_element_one中设置textview的文本值,但不断收到空指针错误。我做错了什么?

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder1=null;
    View row = convertView;
    LayoutInflater inflater = null;

    if(row==null)
    {

        if(getItemViewType(position)==0)
        {
            holder1 = new ViewHolder();
            row= LayoutInflater.from(context).inflate(
                    R.layout.profile_element_one, parent, false);
            holder1.Name = (TextView)row.findViewById(R.id.tv_profile_firstnameLastname);


        }
        else
        {
            row= LayoutInflater.from(context).inflate(
                    R.layout.profile_element_two, parent, false);
        }

    }
    else
    {
        if(position ==1)
        {
            holder1 = (ViewHolder) row.getTag();
        }
     }



    if(position ==1)
    {
        holder1.Name.setText(  this.obj.getFirst_name() +this.obj.getLast_name());

    }




    return row;
}



static  public class ViewHolder {
    TextView Name;

}





            @Override
public int getItemViewType(int position) {

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

2 个答案:

答案 0 :(得分:0)

您需要覆盖getViewTypeCountgetItemViewType方法,以便向适配器说明您的listview行需要不同的布局:

@Override
public int getViewTypeCount() {
    return 2; // meaning that you have two kind of row
}

@Override
public int getItemViewType(int position) {
    return (condition) ? 0 : 1; // condition : is a condition to know each row is being created
}

要小心:上一个方法中返回的整数是从零开始的编号!!!

答案 1 :(得分:0)

只需删除空检查就可以了:

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder1=null;
    View row = convertView;
    LayoutInflater inflater = null;

        if(position==0)
        {
            holder1 = new ViewHolder();
            row= LayoutInflater.from(context).inflate(
                    R.layout.profile_element_one, parent, false);
            holder1.Name = (TextView)row.findViewById(R.id.tv_profile_firstnameLastname);


        }
        else
        {
            row= LayoutInflater.from(context).inflate(
                    R.layout.profile_element_two, parent, false);
        }


        if(position ==0)
        {
            holder1 = (ViewHolder) row.getTag();

        holder1.Name.setText(  this.obj.getFirst_name() +this.obj.getLast_name());

    }




    return row;
}