這兩天有比較閑就整理了一下最近新寫的一個(gè)Recyclview復(fù)雜布局器一。上一個(gè)項(xiàng)目就是由于同事把布局寫死還不支持實(shí)時(shí)刷新導(dǎo)致改了又改。這回打算寫一下recyclview的多個(gè)布局探越。首先查了一下相關(guān)資料,當(dāng) item 的布局方式不一樣的時(shí)候,需在 onCreateViewHolder 中 通過參數(shù) viewType 判斷布局類型坷襟。
@Overridepublic intgetItemViewType(intposition) {returnhomeKinds.get(position).getType();}
該方法返回的就是布局類型,然后在onCreateViewHolder 中進(jìn)行判斷
@OverridepublicRecyclerView.ViewHolderonCreateViewHolder(ViewGroup parent, intviewType) {
? ? View view =null;RecyclerView.ViewHolder holer =null;Log.e("onCreateViewHolder: ",viewType +"");
switch(viewType) {
caseHomeBean.ARTICLE:? ?
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_article,parent, false);
holer =newHAHolder(view,myItemClickListener);break;
caseHomeBean.HOSPTAL:? ? ??
?view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_teethhos,parent, false);
holer =newTTHolder(view,myItemClickListener);
break;
caseHomeBean.LIVE:? ? ? ? ? ?
?view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_live,parent, false);
holer =newHLHolder(view,myItemClickListener);
break;
caseHomeBean.CIRCLE:? ? ? ? ? ?
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_frinder,parent, false);
holer =newFHolder(view,myItemClickListener);
break;
caseHomeBean.ONLINE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_homeonline,parent, false);
holer =newHOHolder(view,myItemClickListener);break;}
return holer;
}
可以看到我這里有5個(gè)不一樣的item生年,接下來就是為每個(gè)不同的布局加載數(shù)據(jù):
public voidonBindViewHolder(RecyclerView.ViewHolder holder, intposition) {
switch(getItemViewType(position)) {
caseHomeBean.ARTICLE:
HAHolder hlHolder = (HAHolder) holder;
hlHolder.name.setText(homeKinds.get(position).getIconname());
Glide.with(mContext).load(homeKinds.get(position).getIconimage()).into(hlHolder.icon);
Glide.with(mContext).load(homeKinds.get(position).getArticleimage()).into(hlHolder.articleimage);
hlHolder.articletime.setText(homeKinds.get(position).getArticletime());
hlHolder.articletext.setText(homeKinds.get(position).getArticlecontent());
break;
}
由于代碼太多就不全部貼在這了婴程;
下面給大家看一下數(shù)據(jù)對象的部分代碼;
數(shù)據(jù)類型抱婉,由于返回的是5個(gè)對象档叔。自己就又寫了一個(gè)對象所有數(shù)據(jù)都添加到自己的Bean里:
public classHomeBean {
public static final intARTICLE=0;//view類型0
public static final intHOSPTAL=1;//view類型2
public static final intLIVE=2;//view 類型3
public static final intCIRCLE=3;//view類型2
public static final intONLINE=4;//view 類型3
省略部分?jǐn)?shù)據(jù)代碼
}
接下來給大家看一下效果
本人也是第一次寫這種多布局的recyclview桌粉,有不足的地方希望大家多多包涵,同事也希望大家能多給建議。