//在開發過程中,多佈局顯示item是非常重要的,下面的程式碼是自定義的adapter顯示垂直和水平佈局下的item
public class MyAdapter extends BaseAdapter {
private final List<AnimaDec.ResultBean.BookListBean> list;
private final Context context;
//兩種佈局
private int typeTotal=2;
//水平佈局的索引
private final int atype=0;
//垂直佈局的索引
private final int btype=1;
public MyAdapter(Context context, List<AnimaDec.ResultBean.BookListBean> list) {
this.context=context;
this.list=list;
}
public void addlist(List<AnimaDec.ResultBean.BookListBean> list2){
list.addAll(list2);
}
//list數量
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
//佈局型別
@Override
public int getItemViewType(int position) {
AnimaDec.ResultBean.BookListBean bookListBean = list.get(position);
String type = bookListBean.getArea();
if(type.equals("國漫"))
{
return atype;
}
else
{
return btype;
}
}
//佈局總數
@Override
public int getViewTypeCount() {
return typeTotal;
}
//自定義佈局getView
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
//優化自定義佈局
ViewHolder1 vh1=null;
ViewHolder2 vh2=null;
//獲得佈局型別總數
int type = getItemViewType(i);
if(view==null) {
switch (type) {
case atype:
vh1 = new ViewHolder1();
view = View.inflate(context, R.layout.horizontal_item, null);
vh1.tv_title = view.findViewById(R.id.tv_title);
vh1.tv_kind = view.findViewById(R.id.tv_king);
vh1.iv_horizontal = view.findViewById(R.id.iv_horizontal);
view.setTag(vh1);
break;
case btype:
vh2 = new ViewHolder2();
view = View.inflate(context, R.layout.vertical_item, null);
vh2.tv_title2 = view.findViewById(R.id.tv_title2);
vh2.tv_kind2 = view.findViewById(R.id.tv_king2);
vh2.iv_vertical = view.findViewById(R.id.iv_vertical);
view.setTag(vh2);
break;
}
}
else
{
switch (type){
case atype:
vh1= (ViewHolder1) view.getTag();
break;
case btype:
vh2= (ViewHolder2) view.getTag();
break;
}
}
//獲得當前物件
AnimaDec.ResultBean.BookListBean listBean = list.get(i);
switch (type){
case atype:
//修改文字內容
vh1.tv_title.setText(listBean.getName());
vh1.tv_kind.setText(listBean.getArea());
//使用ImageLoader載入佈局(ImageLoader看文章列表有介紹)
ImageLoader.getInstance().displayImage(listBean.getCoverImg(),vh1.iv_horizontal);
break;
case btype:
vh2.tv_title2.setText(listBean.getName());
vh2.tv_kind2.setText(listBean.getArea());
ImageLoader.getInstance().displayImage(listBean.getCoverImg(),vh2.iv_vertical);
break;
}
return view;
}
//優化類
class ViewHolder1{
TextView tv_title;
TextView tv_kind;
ImageView iv_horizontal;
}
class ViewHolder2{
TextView tv_title2;
TextView tv_kind2;
ImageView iv_vertical;
}
}
//自定義佈局需要注意:有幾種佈局就需要幾個優化類。