多条目 两个布局的BaseAdapter

public class NewsAdapter extends BaseAdapter {

  private List mDatas;
  private Context context;
  // 0 - count-1
  private final int TT_ITEM = 0;
  private final int GN_ITEM = 1;
  private final int ITEM_COUNT = 2;

  //展示 两种类型条目:文本    文本+图片

  public NewsAdapter(Context context) {
    this.context = context;
    mDatas = new ArrayList<>();
  }

  public void setDatas(List datas) {
    this.mDatas = datas;
    notifyDataSetChanged();
  }

  @Override public int getViewTypeCount() {
    return ITEM_COUNT;
  }

  @Override public int getItemViewType(int position) {
    return getItem(position).isTT() ? TT_ITEM : GN_ITEM;
  }

  @Override public int getCount() {
    return mDatas.size();
  }

  @Override public NewsResponseBean.NewsItem getItem(int position) {
    return mDatas.get(position);
  }

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

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;

//单一职责

//1 创建item

if (convertView == null) {
  convertView = LayoutInflater.from(context).inflate(
      getItemViewType(position) == GN_ITEM ? R.layout.item_gn : R.layout.item_tt
      , parent, false);
  viewHolder = new ViewHolder(convertView);
} else {
  viewHolder = (ViewHolder) convertView.getTag();
}

viewHolder.bind(getItem(position));

return convertView;
 }

 class ViewHolder {
    //如果是国内新闻,icon不为空;否则icon为空
    ImageView icon;

TextView title;
TextView date;

public ViewHolder(View convertView) {
  title = convertView.findViewById(R.id.title);
  date = convertView.findViewById(R.id.date);
  //可能为空
  icon = convertView.findViewById(R.id.icon);
  convertView.setTag(this);
}

public void bind(NewsResponseBean.NewsItem newsItem) {
  title.setText(newsItem.getTitle());
  date.setText(newsItem.getDate());
  if(icon != null) {
    //加载图片
    icon.setImageResource(R.mipmap.ic_launcher);
  }
 /* if (getItemViewType(position) == GN_ITEM) {
    //加载图片
  }*/
}
}

国内的子布局




  

  

  


头条的子布局




  

  


你可能感兴趣的:(多条目 两个布局的BaseAdapter)