首页 > 代码库 > ListView实现不同布局的显示

ListView实现不同布局的显示

ListView进行不同布局的显示,就需要重写5种方法,本文以两种布局为例

技术分享

利用假数据进行模拟:

技术分享

添加适配器

技术分享

class MyBaseAdapter extends BaseAdapter{

@Override
public int getCount() {
return mData.size()+mReshdata.size();
}

@Override
public Object getItem(int i) {

return null;

}

@Override
public long getItemId(int i) {
return 0;
}

/**
*
* @return返回两种类型布局
*/
@Override
public int getViewTypeCount() {
return 2;
}

/**
* 不同布局绘制状况
// * @param position
* @return
*/
@Override
public int getItemViewType(int position) {
Log.d("TAG","POSITO="+position+","+"getcount="+mData.size());

if (position<mData.size()){
return first;
}else {
return second;
}

}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Log.d("TAG","I="+i);
int itemViewType = getItemViewType(i);
Log.d("TAG","itemViewType="+itemViewType);
ViewHolder holder = null;
ViewHolderTwo holder_se = null;
if (view == null){
switch (itemViewType){
case first:
holder = new ViewHolder();
view = View.inflate(getApplicationContext(), R.layout.item_lv, null);
holder.tv_data = http://www.mamicode.com/(TextView) view.findViewById(R.id.tv_sj);
view.setTag(holder);
break;
case second:
holder_se = new ViewHolderTwo();
view = View.inflate(getApplicationContext(), R.layout.item_second, null);
holder_se.tv_second = (TextView) view.findViewById(R.id.tv_second);
view.setTag(holder_se);
break;
default:
break;
}
}else {
switch (itemViewType){
case first:
holder = (ViewHolder) view.getTag();
break;
case second:
holder_se = (ViewHolderTwo) view.getTag();
break;
default:
break;
}
}
switch (itemViewType){
case first:
String s = mData.get(mData.size()-1);//mData.get(i)
holder.tv_data.setText(s);
break;
case second:

Log.d("TAG","i-mData.size()="+ (i-mData.size()));

String second = mReshdata.get(i-mData.size());
holder_se.tv_second.setText(second);
break;
default:
break;
}
return view;
}
}
class ViewHolder{
TextView tv_data;

}
class ViewHolderTwo{
TextView tv_second;
}
进行不同布局的加载就实现了:
布局用的就是简单的TextView就不列出了。

技术分享

同理实现多种类型,按照这样的逻辑都可以实现。



ListView实现不同布局的显示