我对recyclerview有疑问,我想在我的recyclerview中放置广告(不是google的原生广告)。广告来自API。我想将这些广告放在我的Recyclerview中,其中包含来自API的新闻。
所以,我有两次来自api的回复,以进入recyclerview。以下是我的新闻回复和广告回复。
新闻回复api https://jsonblob.com/7ba93af8-6884-11e8-94d5-4b6d8b2939b5
广告回复api https://jsonblob.com/5010a591-6884-11e8-94d5-6505b8737ba5
我想在每5条新闻中展示我的广告,在我的回收者视图之间投放广告的最佳方式是什么?
[EDI 1] 这是我的适配器
package com.asosiasidosenindonesia.adi.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.asosiasidosenindonesia.adi.model.response.AdsResponse;
import com.bumptech.glide.Glide;
import com.asosiasidosenindonesia.adi.R;
import com.asosiasidosenindonesia.adi.activity.DetailNewsActivity;
import com.asosiasidosenindonesia.adi.config.Constant;
import com.asosiasidosenindonesia.adi.model.response.NewsResponse;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Personal on 13/04/18.
*/
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public final String TAG = getClass().getSimpleName();
/*
*
* VIEW TYPE FOR ITEM RECYCLREVIEW
* There is two common item type :
* 1) CONTENT_ITEM_VIEW_TYPE = FOR ITEM IN RECYCLERVIEW
* 2) ADS_ITEM_VIEW_TYPE = FOR ADS TO SHOW IN RECYCLERVIEW
*/
private static final int CONTENT_ITEM_VIEW_TYPE = 0;
private static final int ADS_ITEM_VIEW_TYPE = 1;
private static final int ADS_LIST_DALTA = 4;
Context context;
public int i = 0;
//Collection of data
List<NewsResponse.Data> datas = new ArrayList<>();
List<AdsResponse.Data> adsDatas = new ArrayList<>();
public NewsAdapter(Context context, List<NewsResponse.Data> datas, List<AdsResponse.Data> adsDatas) {
this.context = context;
this.datas = datas;
this.adsDatas = adsDatas;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//For Content News
View content = LayoutInflater.from(context).inflate(R.layout.single_item_news,parent,false);
//For Ads
View ads = LayoutInflater.from(context).inflate(R.layout.ads_320_150,parent,false);
switch (viewType){
case CONTENT_ITEM_VIEW_TYPE:
NewsHolder newsHolder = new NewsHolder(content);
return newsHolder;
case ADS_ITEM_VIEW_TYPE:
AdsHolder adsHolder = new AdsHolder(ads);
return adsHolder;
default:
AdsHolder newsHolder1 = new AdsHolder(ads);
return newsHolder1;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof NewsHolder){
((NewsHolder) holder).populateNewsHolder(datas.get(getRealPosition(position)));
}else if (holder instanceof AdsHolder){
if (i < 5){
((AdsHolder) holder).populateAds(adsDatas.get(i));
}
i++;
}
}
private int getRealPosition(int position){
if (ADS_LIST_DALTA == 0){
return position;
}else{
return position - position/ADS_LIST_DALTA;
}
}
@Override
public int getItemCount() {
int additionalContent = 0;
if (datas.size() > 0 && ADS_LIST_DALTA > 0 && datas.size() > ADS_LIST_DALTA){
additionalContent = datas.size() / ADS_LIST_DALTA;
}
return datas.size() + additionalContent;
}
@Override
public int getItemViewType(int position) {
if (position > 0 && position % ADS_LIST_DALTA == 0){
return ADS_ITEM_VIEW_TYPE;
}
return CONTENT_ITEM_VIEW_TYPE;
}
/*View Holder Type For News*/
public class NewsHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_slug)
TextView tvSlug;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_kategori)
TextView tvKategori;
@BindView(R.id.tv_tgl_event)
TextView tvTglNews;
@BindView(R.id.iv_news)
ImageView ivNews;
public NewsHolder(final View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, tvTitle.getText().toString(), Toast.LENGTH_SHORT).show();
Intent toDetail = new Intent(itemView.getContext(), DetailNewsActivity.class);
toDetail.putExtra(Constant.SLUG, tvSlug.getText().toString());
itemView.getContext().startActivity(toDetail);
}
});
}
public void populateNewsHolder(NewsResponse.Data model){
tvSlug.setText(model.getSlug());
tvTitle.setText(model.getTitle());
tvTglNews.setText(model.getCreatedAt().getDateFriendly()+", "+model.getCreatedAt().getDate());
tvKategori.setText("#"+model.getKategori().getNama());
Glide.with(context)
.load(model.getFoto())
.dontAnimate()
.placeholder(R.drawable.banner)
.error(R.drawable.banner)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(ivNews);
}
}
/*View Holder Type For Ads*/
public class AdsHolder extends RecyclerView.ViewHolder{
@BindView(R.id.iv_ads)
ImageView ivAds;
@BindView(R.id.tv_name)
TextView tvName;
public AdsHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, tvName.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void populateAds(AdsResponse.Data data){
Glide.with(context)
.load(data.getAdsImage())
.dontAnimate()
.into(ivAds);
tvName.setText(data.getImageName());
}
}
public void resetAdsPosition(){
i = 0;
}
}
这是我获取数据的片段
package com.asosiasidosenindonesia.adi.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.asosiasidosenindonesia.adi.activity.DetailNewsActivity;
import com.asosiasidosenindonesia.adi.config.Constant;
import com.asosiasidosenindonesia.adi.model.response.AdsResponse;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.google.gson.GsonBuilder;
import com.asosiasidosenindonesia.adi.R;
import com.asosiasidosenindonesia.adi.adapter.EventAdapter;
import com.asosiasidosenindonesia.adi.adapter.NewsAdapter;
import com.asosiasidosenindonesia.adi.config.PrefHandler;
import com.asosiasidosenindonesia.adi.model.response.EventResponse;
import com.asosiasidosenindonesia.adi.model.response.HeadlineResponse;
import com.asosiasidosenindonesia.adi.model.response.NewsResponse;
import com.asosiasidosenindonesia.adi.network.NetworkClient;
import com.asosiasidosenindonesia.adi.network.ServiceGeneratorAuth;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import dmax.dialog.SpotsDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsFragment extends Fragment {
private final String TAG = getClass().getSimpleName();
private SpotsDialog spotDialogs;
private int page = 1, adsSize = 5;
private boolean itShouldLoadMore = true;
Context context;
EventAdapter adapter;
NewsAdapter adapterNews;
List<NewsResponse.Data> datasNews = new ArrayList<>();
List<HeadlineResponse.Data> datasHeadlines = new ArrayList<>();
List<AdsResponse.Data> dataAds = new ArrayList<>();
@BindView(R.id.nested_scroll_view)
NestedScrollView nestedScrollView;
@BindView(R.id.rv_news)
RecyclerView rvNews;
@BindView(R.id.swipe_refresh_layout)
SwipeRefreshLayout swipeRefreshLayout;
@BindView(R.id.image_slider)
SliderLayout imageSlider;
@BindView(R.id.cv_empty)
CardView cvEmpty;
@BindView(R.id.tv_message)
TextView tvMessage;
public NewsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, container, false);
init(view);
getNewsHeadlines();
getNews();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
datasNews.clear();
adapterNews.notifyDataSetChanged();
page = 1;
itShouldLoadMore = true;
getNews();
swipeRefreshLayout.setRefreshing(false);
}
});
// Inflate the layout for this fragment
return view;
}
/*First inisialize*/
private void init(View view) {
ButterKnife.bind(this, view);
PrefHandler.init(getActivity());
spotDialogs = new SpotsDialog(getActivity());
//News
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
rvNews.setLayoutManager(linearLayoutManager);
rvNews.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
rvNews.setHasFixedSize(true);
adapterNews = new NewsAdapter(context,datasNews, dataAds);
rvNews.setAdapter(adapterNews);
rvNews.setNestedScrollingEnabled(false);
nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if(v.getChildAt(v.getChildCount() - 1) != null) {
if ((scrollY >= (v.getChildAt(v.getChildCount() - 1).getMeasuredHeight() - v.getMeasuredHeight())) &&
scrollY > oldScrollY) {
if (itShouldLoadMore == true){
getNewsMore();
Toast.makeText(context, "Memuat event yang diikuti lainnya..", Toast.LENGTH_SHORT).show();
}else{
// Toast.makeText(context, "Sudah tidak ada data yang dimuat..", Toast.LENGTH_SHORT).show();
}
}
}
}
});
}
private void getAds() {
dataAds.clear();
int i = 0;
while (i < 5){
AdsResponse.Data data = new AdsResponse.Data(R.drawable.ads_320_150, "Iklan "+i, "https://anggit.me");
dataAds.add(data);
i++;
}
}
/*Get News Headlines*/
private void getNewsHeadlines(){
datasHeadlines.clear();
Call<HeadlineResponse> call = ServiceGeneratorAuth.createService(NetworkClient.class, PrefHandler.getTokenKey(), getActivity())
.getNewsHeadlines("desc", "", "headline");
call.enqueue(new Callback<HeadlineResponse>() {
@Override
public void onResponse(Call<HeadlineResponse> call, Response<HeadlineResponse> response) {
if (response.isSuccessful()){
Log.d(TAG, "onResponse: "+new GsonBuilder().setPrettyPrinting().create().toJson(response.body()));
int i = 0;
while (i < response.body().getData().size() && i <= 5){
HeadlineResponse.Data data = new HeadlineResponse.Data(response.body().getData().get(i).getUpdatedAt(),response.body().getData().get(i).getCreatedAt(),
response.body().getData().get(i).getKategori(),response.body().getData().get(i).getProvinsi(),response.body().getData().get(i).getUser(),
response.body().getData().get(i).getHeadline(),response.body().getData().get(i).getPageViews(),response.body().getData().get(i).getDeskripsi(),
response.body().getData().get(i).getFoto(),response.body().getData().get(i).getSlug(),response.body().getData().get(i).getTitle());
datasHeadlines.add(data);
Bundle bundle = new Bundle();
bundle.putString(Constant.ID_EVENT, response.body().getData().get(i).getSlug());
TextSliderView textSliderView = new TextSliderView(context);
textSliderView.description(response.body().getData().get(i).getTitle())
.bundle(bundle)
.image(response.body().getData().get(i).getFoto())
.empty(R.drawable.banner)
.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
@Override
public void onSliderClick(BaseSliderView slider) {
Intent toDetail = new Intent(context, DetailNewsActivity.class);
toDetail.putExtra(Constant.SLUG, slider.getBundle().getString(Constant.ID_EVENT));
getActivity().startActivity(toDetail);
}
});
imageSlider.setDuration(500000);
imageSlider.addSlider(textSliderView);
i++;
}
//Cek apakah headline ada
if (datasHeadlines.size() == 0){
Log.d(TAG, "onResponse: Gak ada");
TextSliderView textSliderView = new TextSliderView(context);
textSliderView.description("")
.image(R.drawable.banner)
.empty(R.drawable.banner);
imageSlider.setDuration(500000);
imageSlider.addSlider(textSliderView);
}else{
Log.d(TAG, "onResponse: Ada");
}
}else{
Log.d(TAG, "onResponse: Gagal");
}
}
@Override
public void onFailure(Call<HeadlineResponse> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
/*Get News First Page*/
private void getNews(){
spotDialogs.show();
datasNews.clear();
Call<NewsResponse> call = ServiceGeneratorAuth.createService(NetworkClient.class, PrefHandler.getTokenKey(), getActivity())
.getNews("desc");
call.enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
spotDialogs.dismiss();
if (response.isSuccessful()){
Log.d(TAG, "onResponse: "+new GsonBuilder().setPrettyPrinting().create().toJson(response.body()));
int i = 0;
while (i < response.body().getData().size()){
NewsResponse.Data data = new NewsResponse.Data(response.body().getData().get(i).getUpdatedAt(),response.body().getData().get(i).getCreatedAt(),
response.body().getData().get(i).getKategori(),response.body().getData().get(i).getProvinsi(),response.body().getData().get(i).getUser(),
response.body().getData().get(i).getHeadline(),response.body().getData().get(i).getCountViewer(),response.body().getData().get(i).getDeskripsi(),
response.body().getData().get(i).getFoto(),response.body().getData().get(i).getSlug(),response.body().getData().get(i).getTitle());
datasNews.add(data);
i++;
}
getAds();
adapterNews.notifyDataSetChanged();
page = response.body().getMeta().getCurrentPage()+1;
if (page >= response.body().getMeta().getLastPage()){
itShouldLoadMore = false;
}else{
itShouldLoadMore = true;
}
if (adapterNews.getItemCount() == 0){
Log.d(TAG, "onResponse: Kosong");
showEmpty();
tvMessage.setText("Belum ada berita hari ini..");
}else{
hideEmpty();
}
}else{
Log.d(TAG, "onResponse: Gagal");
}
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
spotDialogs.dismiss();
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
/*Get Event More Based On Page*/
private void getNewsMore(){
Call<NewsResponse> call = ServiceGeneratorAuth.createService(NetworkClient.class, PrefHandler.getTokenKey(), context)
.getNewsMore(String.valueOf(page), "desc");
call.enqueue(new Callback<NewsResponse>() {
@Override
public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
if (response.isSuccessful()){
Log.d(TAG, "onResponse: "+new GsonBuilder().setPrettyPrinting().create().toJson(response.body()));
int i = 0;
while (i < response.body().getData().size()){
NewsResponse.Data data = new NewsResponse.Data(response.body().getData().get(i).getUpdatedAt(),response.body().getData().get(i).getCreatedAt(),
response.body().getData().get(i).getKategori(),response.body().getData().get(i).getProvinsi(),response.body().getData().get(i).getUser(),
response.body().getData().get(i).getHeadline(),response.body().getData().get(i).getCountViewer(),response.body().getData().get(i).getDeskripsi(),
response.body().getData().get(i).getFoto(),response.body().getData().get(i).getSlug(),response.body().getData().get(i).getTitle());
datasNews.add(data);
i++;
}
adapterNews.resetAdsPosition();
getAds();
adapterNews.notifyDataSetChanged();
page = response.body().getMeta().getCurrentPage()+1;
if (page >= response.body().getMeta().getLastPage()){
itShouldLoadMore = false;
}else{
itShouldLoadMore = true;
}
}else{
Log.d(TAG, "onResponse: Gagal");
}
}
@Override
public void onFailure(Call<NewsResponse> call, Throwable t) {
Log.d(TAG, "onFailure: "+t.getMessage());
}
});
}
@Override
public void onStop() {
imageSlider.stopAutoCycle();
super.onStop();
}
/*Update UI*/
private void showEmpty(){
cvEmpty.setVisibility(View.VISIBLE);
rvNews.setVisibility(View.GONE);
}
private void hideEmpty(){
cvEmpty.setVisibility(View.GONE);
rvNews.setVisibility(View.VISIBLE);
}
}
答案 0 :(得分:1)
我想在我的recyclerview中放置广告
getItemViewType(int position)
这是您必须用来在同一个Recyclerview中显示多个项目
每5件物品在recyclerview内放置广告吗?
在将数据填充到适配器之前,您需要合并来自两者的数据以您需要的格式对其进行排列并执行此操作,您必须使用recyclerview的不同ItemViewType来实现此目的。
例如,您可以参考this