我有一个应用程序,其中包含recyclelerview和progressbar在底部,当我滚动到recyclerview结束它发送服务器请求更多数据,这是正常工作但问题是我想在recyclerview之间随机添加广告位置。我如何在recyclerview中随机添加它。
代码: -
@Override
public int getItemViewType(int position) {
return contacts.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
View view = LayoutInflater.from(activity).inflate(R.layout.item_recycler_view_row, parent, false);
return new UserViewHolder(view);
} else if (viewType == 1) {
View view = LayoutInflater.from(activity).inflate(R.layout.item_loading, parent, false);
return new LoadingViewHolder(view);
} else {
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof UserViewHolder) {
Contact contact = contacts.get(position);
UserViewHolder userViewHolder = (UserViewHolder) holder;
userViewHolder.phone.setText(contact.getEmail());
userViewHolder.email.setText(contact.getPhone());
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
@Override
public int getItemCount() {
return contacts == null ? 0 : contacts.size();
}
答案 0 :(得分:0)
在适配器中,首先需要覆盖getItemViewType()
,例如:
@Override
public int getItemViewType(int position) {
if (contacts.get(position) == null)
return VIEW_TYPE_LOADING;
else if (position % 5 == 0)
return AD_TYPE;
else {
return VIEW_TYPE_ITEM;
}
}
在onCreateViewHolder之后,根据这样的类型膨胀不同的视图:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = null;
if (viewType == AD_TYPE) {
View adView = LayoutInflater.from(parent.getContext()).inflate(R.layout.native_ads, viewGroup, false);
return new ViewHolderAdMob(adView);
} else if (viewType == VIEW_TYPE_ITEM) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_layout, viewGroup, false);
return new UserViewHolder(view);
}else if (viewType == VIEW_TYPE_LOADING) {
view = LayoutInflater.from(activity).inflate(R.layout.item_loading, viewGroup, false);
return new LoadingViewHolder(view);
}
return null;
}
原生广告xml
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
AdViewHolder类
public static class ViewHolderAdMob extends RecyclerView.ViewHolder {
public AdView mAdView;
public ViewHolderAdMob(View view) {
super(view);
mAdView = (AdView) view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
}
}
另外,请不要忘记相应地更改getItemCount()
:return contacts.size()+ (contacts.size() % 5)