适配器中的 AdView 构造函数问题

AdView Constructor issue in Adapter

当我尝试初始化广告时出现以下错误

AdView (Context, android.util.AttributeSet) in AdView cannot be applied to (Context, com.google.android.gms.ads.AdSize).  

这是我的代码

public class NotesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private static final int EMPTY_VIEW = 1;
private static final int DATA_VIEW = 2;
private static final int AD_VIEW = 3;
public List<Note> allnotes;

public NotesAdapter(List<Note> allnotes, Context context) {
    this.allnotes = allnotes;
    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;
    RecyclerView.ViewHolder holder;
    if (viewType == EMPTY_VIEW) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.note_zero, parent, false);
        holder = new emptyViewHolder(view);
    } else if (viewType ==AD_VIEW) {
        view = new AdView(context, AdSize.BANNER);
    } else {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_note_card, parent, false);
        holder = new myViewHolder(view);
    }
    return  holder;
}

AdSize 没有 AdView 构造函数。使用那个:

AdView adView = new AdView(context);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

这里:

new AdView(context, AdSize.BANNER)

您正在使用 com.google.android.gms.ads.AdSize,该方法需要 android.util.AttributeSet。试试这个:

mAdView = new AdView(context);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId("myAdUnitId");

供日后参考:

显然,API 已经更新,现在可用的构造函数是:

AdView(Context context)
   Construct an AdView from code.

AdView(Context context, AttributeSet attrs)
   Construct an AdView from an XML layout.

AdView(Context context, AttributeSet attrs, int defStyle)
   Construct an AdView from an XML layout.

希望对您有所帮助!