本文共 2321 字,大约阅读时间需要 7 分钟。
由于item中converView的复用,所以ListView在展示不同布局的时候,需要在adapter里复写以下方法:getViewTypeCount()和getItemViewType(int position)。有了这个思路就很简单了。adapter代码如下:
package com.example.dyk.listviewtest;import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;import java.util.List;/** * Created by Administrator on 2016/2/27. */public class Adapter extends BaseAdapter { private Listlist; private Context mContext; private LayoutInflater mInflater; private ViewHolder holder; public Adapter(List list, Context mContext) { this.list = list; this.mContext = mContext; mInflater = LayoutInflater.from(mContext); } public void notifyDataSetChanged(List list) { this.list = list; super.notifyDataSetChanged(); } @Override public int getCount() { return list == null ? 0 : list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { if (position == 0) { return 0; } else { return 1; } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == 0) { convertView = mInflater.inflate(R.layout.item, null); } else { if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.items, null); holder.name = (TextView) convertView.findViewById(R.id.name); holder.age = (TextView) convertView.findViewById(R.id.age); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Bean bean = list.get(position); holder.name.setText(bean.getName()); holder.age.setText(bean.getAge()); } return convertView; } public class ViewHolder { TextView name; TextView age; }}
转载地址:http://zxmra.baihongyu.com/