我使用CustomAdapter创建了listView。我正在尝试为列表视图的第一项设置另一个布局。我尝试了位置,但没有帮助。有什么建议?
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
Log.d("Position: ",String.valueOf(position));
if (convertView == null) {
if(position==0)
convertView = inflater.inflate(R.layout.row1, null);
else
convertView = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.nTitle = (TextView) convertView.findViewById(R.id.listTitle);
holder.nDate = (TextView) convertView.findViewById(R.id.listDate);
holder.nCategory = (TextView) convertView.findViewById(R.id.listCategory);
holder.nImage = (ImageView) convertView.findViewById(R.id.listImage);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
if (newsList.get(position) != null) {
holder.imageUrl = newsList.get(position).image;
holder.nTitle.setText(newsList.get(position).title);
holder.nCategory.setText(newsList.get(position).category);
holder.nDate.setText(Base.getInstance(aContext).getDateString(newsList.get(position).date));
holder.nImage.setImageResource(R.drawable.photo_bg);
}
return convertView;
}
答案 0 :(得分:4)
你可以这样做
在适配器中有以下内容
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
覆盖getItemViewType
int type;
@Override
public int getItemViewType(int position) {
if (position== 0){ // position 0
type = TYPE_ITEM1;
} else {
type = TYPE_ITEM2;
}
return type;
}
并覆盖getViewTypeCount
@Override
public int getViewTypeCount() {
return 2; // we have 2 types
}
在getView
int type = getItemViewType(position);
// instead of if else you can use a case
if (convertView == null) {
if (type == TYPE_ITEM1) {
//inflate layout of type1
}
if (type == TYPE_ITEM2) {
//inflate layout of type2
}
// Your rest of the code
文件:
https://developer.android.com/reference/android/widget/Adapter.html#getItemViewType%28int%29
https://developer.android.com/reference/android/widget/Adapter.html#getViewTypeCount%28%29
同时浏览此视频。谈话中涵盖了大多数概念
https://www.youtube.com/watch?v=wDBM6wVEO70
使用RecyclerView
代替ListView
会更好
答案 1 :(得分:1)
如果只有第一项与ListView
中的其他项目不同,建议您使用addHeaderView
而不是在getView
中对其进行充气。首先在Activity
或Fragment
中对该视图进行通知,然后再将其添加到该列表视图中。
关注this.