I have implemented a native ad in my ListView, it works fine but reloads every time it comes to focus. Is there any way I can hold the instance or the view so it doesn't reload every time. Or can I block the recreation of the view?
class CustomAdapter extends BaseAdapter {
String content, currentFile, pv;
@Override
public int getCount() {
return fileList.size();
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (i == 0) {
if (isNetworkAvailable()) {
// ad loads here
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.native_ad_item, null);
final CardView cardView = (CardView) view.findViewById(R.id.card_view);
NativeExpressAdView adView = (NativeExpressAdView) view.findViewById(R.id.nativeAd);
AdRequest request = new AdRequest.Builder().addTestDevice("264647BDFDDB6FBB0F34C797D5D53A4D").build();
adView.loadAd(request);
}
} else {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.purchased_list_item, null);
// rest of the code
}
return view;
}
The ListView reuses the child views created in getView() and sends them as the second parameter (which is actually called convertView) of that method. You can check if that View is not null and use it instead of creating a new one each time. You can see more details in the answers to this question: What is the purpose of `convertView` in ListView adapter?