Admob横幅广告使我的Recyclerview滞后

时间:2018-07-04 16:17:48

标签: android performance android-recyclerview admob

我正在我的android应用中显示横幅广告。我遵循了官方文档来实施admob横幅contentView广告,并成功加载了广告,但现在我的recyclerview像地狱一样滞后了。如果我从代码中删除广告,滚动会变得很顺畅。请帮助我解决这个问题。

这是我的片段类

public class WallpaperFragment extends Fragment {

private RecyclerView recyclerView;
private DatabaseReference wallRef;
private String category;
private FirebaseAuth mAuth;

private final String CATEGORY = "Category";

private Context context;
private ArrayList<Object> modelList = new ArrayList<>();
private GridLayoutManager manager;

// The number of native ads to load and display.
public int NUMBER_OF_ADS = 5;

// List of native ads that have been successfully loaded.
private List<NativeAd> mNativeAds = new ArrayList<>();
private WallpaperAdapter adapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fg_wallpaper, container, false);

    category = "Recent";
    init(view);
    Util.showDialog(context, "Loading wallpapers...");

    manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            return (position % (SPACE_BETWEEN_ADS + 1) == SPACE_BETWEEN_ADS) ? 2 : 1;
        }
    });

    setScrollListener();
    initializeFirebaseDatabase();

    return view;
}

private void init(View view) {
    context = getContext();
    MobileAds.initialize(context, getString(R.string.admob_app_id));
    wallRef = FirebaseDatabase.getInstance().getReference().child(WALL).child(CATEGORY).child(category).getRef();
    mAuth = FirebaseAuth.getInstance();

    recyclerView = view.findViewById(R.id.recyclerView);
    manager = new GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(manager);
    recyclerView.addItemDecoration(new GridItemDecor(0));
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemAnimator(null);
}

private void setScrollListener() {
    recyclerView.addOnScrollListener(new HidingScrollListener() {
        @Override
        public void onHide() {
            if (context instanceof ToolbarShowHideListener) {
                ((ToolbarShowHideListener) context).hideBottomNavigation();
            }
        }

        @Override
        public void onShow() {
            if (context instanceof ToolbarShowHideListener) {
                ((ToolbarShowHideListener) context).showBottomNavigation();
            }
        }
    });
}

private void initializeFirebaseDatabase() {
    mNativeAds.clear();
    wallRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            modelList.clear();
            for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                WallpaperModel model = childDataSnapshot.getValue(WallpaperModel.class);
                modelList.add(model);
            }

            NUMBER_OF_ADS = modelList.size() / 2;
            loadNativeAd();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

private void loadNativeAd() {
    loadNativeAd(0);
}

private void insertAdsInMenuItems() {
    if (mNativeAds.size() <= 0) {
        return;
    }

    int offset = (modelList.size() / mNativeAds.size()) + 1;
    int index = 2;
    for (NativeAd ad : mNativeAds) {
        modelList.add(index, ad);
        index = index + offset;
    }
    if (adapter == null) {
        adapter = new WallpaperAdapter(context, modelList, Objects.requireNonNull(mAuth.getCurrentUser()).getUid(), true, WALLPAPER_FRAGMENT);
        recyclerView.setAdapter(adapter);
    } else {
        adapter.updateList(modelList);
    }
}

private void loadNativeAd(final int adLoadCount) {

    if (adLoadCount >= NUMBER_OF_ADS) {
        insertAdsInMenuItems();
        return;
    }

    AdLoader.Builder builder = new AdLoader.Builder(context, /*getString(R.string.ad_unit_id)*/"ca-app-pub-3940256099942544/2247696110");
    AdLoader adLoader = builder.forContentAd(new NativeContentAd.OnContentAdLoadedListener() {
        @Override
        public void onContentAdLoaded(NativeContentAd ad) {
            // A content ad loaded successfully, call this method again to
            // load the next ad in the items list.
            mNativeAds.add(ad);
            loadNativeAd(adLoadCount + 1);
        }
    }).withAdListener(new AdListener() {
        @Override
        public void onAdFailedToLoad(int errorCode) {
            // A native ad failed to load. Call this method again to load
            // the next ad in the items list.
            Log.e("MainActivity", "The previous native ad failed to load. Attempting to" +
                    " load another.");
            loadNativeAd(adLoadCount + 1);
        }
    }).build();

    // Load the Native Express ad.
    adLoader.loadAd(new AdRequest.Builder().addTestDevice("9F50A23B86C21B90330202FAECE3C331").build());
}

}

这是我的适配器类,

public class WallpaperAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private int height, fragment_id;
private String uId;
private Animation fadeout, fadein;
private DatabaseReference favCheckRef;
private final String CATEGORY = "Category";
private ArrayList<Object> modelList;
private boolean showLikeBtn;

public WallpaperAdapter(Context context, ArrayList<Object> modelList, String uId, boolean showLikeBtn, int fragment_id) {
    this.context = context;
    this.modelList = modelList;
    this.uId = uId;
    this.showLikeBtn = showLikeBtn;
    height = context.getResources().getDisplayMetrics().heightPixels;
    fadeout = AnimationUtils.loadAnimation(context, R.anim.anim_fade_out);
    fadein = AnimationUtils.loadAnimation(context, R.anim.anim_fade_in);
    favCheckRef = FirebaseDatabase.getInstance().getReference().child(WALL).child(USER)
            .child(uId).child(FAVOURITES).getRef();
    this.fragment_id = fragment_id;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    switch (viewType) {
        case NATIVE_CONTENT_AD_VIEW_TYPE:
            View nativeContentLayoutView = LayoutInflater.from(
                    parent.getContext()).inflate(R.layout.ad_content,
                    parent, false);
            return new NativeContentAdViewHolder(nativeContentLayoutView);
        case MENU_ITEM_VIEW_TYPE:
            // Fall through.
        default:
            View dataView = LayoutInflater.from(context).inflate(R.layout.single_wallpaper_unit, parent, false);
            return new ViewHolder(dataView);
    }
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    int viewType = getItemViewType(position);
    Util.dismissDialog();

    switch (viewType) {

         case NATIVE_CONTENT_AD_VIEW_TYPE:
            NativeContentAd contentAd = (NativeContentAd) modelList.get(position);
            populateAdView(contentAd, (NativeContentAdView) holder.itemView);
            break;

        case MENU_ITEM_VIEW_TYPE:
            // fall through
        default:
            final ViewHolder wallHolder = (ViewHolder) holder;
            WallpaperModel model = (WallpaperModel) modelList.get(position);

            wallHolder.wallpaper.getLayoutParams().height = (int) (height / 2.5);
            wallHolder.name.setText(model.getName());
            favCheck(wallHolder, model);
            Glide.with(wallHolder.wallpaper.getContext())
                    .load(model.getThumbnail())
                    .into(wallHolder.wallpaper);
            break;


    }
}

@Override
public int getItemViewType(int position) {
    Object recyclerViewItem = modelList.get(position);
    if (recyclerViewItem instanceof NativeContentAd) {
        return NATIVE_CONTENT_AD_VIEW_TYPE;
    }
    return MENU_ITEM_VIEW_TYPE;
}

@Override
public int getItemCount() {
    return modelList.size();
}
private void populateAdView(NativeContentAd ad,NativeContentAdView adView){
    ((TextView) adView.getHeadlineView()).setText(ad.getHeadline());
    List<NativeAd.Image> images = ad.getImages();

    if (images.size() > 0) {
        ((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable());
    }
    adView.setNativeAd(ad);
}

public class ViewHolder extends RecyclerView.ViewHolder {

    TextView name;
    ImageView wallpaper, favouriteIcon;

    private ViewHolder(View itemView) {
        super(itemView);

        wallpaper = itemView.findViewById(R.id.wallpaper);
        name = itemView.findViewById(R.id.name);
        favouriteIcon = itemView.findViewById(R.id.favouriteIcon);
    }
}

public class NativeContentAdViewHolder extends RecyclerView.ViewHolder {
    NativeContentAdViewHolder(View view) {
        super(view);
        NativeContentAdView adView = (NativeContentAdView) view;
        adView.setHeadlineView(adView.findViewById(R.id.contentad_headline));
        adView.setImageView(adView.findViewById(R.id.contentad_image));
    }
}

}

1 个答案:

答案 0 :(得分:1)

您正在加载本地快递,而不是横幅。

问题在于广告具有图像,就像普通的查看器一样,您必须处理图像的缓存,我发现您已经在使用滑行...

此外,显示广告ID也不是一个好主意。

最后一点,NONE很重要,因为不赞成使用原生快递广告,并且无论如何都无法正常工作。

另一种选择是使用Native Ads Advance,但是除非下载量达到几百万,否则您将无法使用它-look here

Note: Native Ads Advanced is currently released to a limited set of publishers. If you're interested in participating, reach out to your account manager to discuss the possibility.

我建议使用支持本地广告的Appodeal之类的广告提供商。