具有多个布局的Android ListView
作者:互联网
我必须显示具有不同视图类型的列表.因此,我必须定义一个带有适配器的ListView,在其中必须膨胀多个视图.我已经经历了example,但是问题是我的列表不对称,就像示例在4个项目之后每次重复标题一样.所以我面临在getView()中重复使用项目的问题
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_1:
convertView = mInflater.inflate(R.layout.item1, null);
.......
break;
case TYPE_2:
convertView = mInflater.inflate(R.layout.item2, null);
.......
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
............
............
}
现在,如果convertView不为null,但是之前使用的项类型不同,则布局将不匹配.此代码将如何处理此问题?
解决方法:
您可以查看此示例适配器. getViewTypeCount方法返回您的不同类型的行. getItemViewType方法,如果position等于0,则对第一行布局进行膨胀,否则对其他行布局进行膨胀.您可以自定义此代码示例.
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
/**
* Created by MustafaS on 9.2.2015.
*/
public class CustomArrayAdapter extends ArrayAdapter<YourModel> {
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
}
else {
return 1;
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
if (type == 0) {
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.listview_first_row, parent, false);
viewHolderFirst = new ViewHolderFirst();
convertView.setTag(viewHolderFirst);
}
else {
viewHolderFirst = (ViewHolderFirst) convertView.getTag();
}
}
else {
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.listview_other_row, parent, false);
viewHolder = new ViewHolder();
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
}
return convertView;
}
protected class ViewHolderFirst {
private RunnableViewPager pager;
private CircleIndicator indicator;
}
protected class ViewHolder {
private ImageView imageviewRestaurant;
private TextView textviewRestaurantName;
private TextView textviewType;
private TextView textviewPrice;
private TextView textviewDistance;
private ImageView imageviewCall;
private ImageView imageviewCalendar;
}
}
标签:layout-inflater,listview,baseadapter,getview,android 来源: https://codeday.me/bug/20191120/2044615.html