Search code examples
androidviewadmobandroid-canvasextends

Adding admob to a canvas in a extends View class


I am trying to implement admob in my app, but I can't get it working.

I have a Class A, which is the main class, it extends activity. I have a Class B, which is the class that is called when the application start. I have the following piece of code in class A to archive this:

B b = new B(this);
setContentView(B);

In class B I have a canvas with test and bitmaps. I want to put an ad on the canvas with admob, but I can't archive this. Class B:

private AdView adView;
int[] degree = { 90, 180, 270, 360 };// random graden eindposities pijl
// int width, height;
Random rand = new Random();
Typeface font;
Matrix matrix = new Matrix();// degree,x,yaxis
Region region;// region die klikbaar is om het pijl te bewegen
AlertDialog alertDialog;
LinearLayout layout;
    
public YesNo(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}
    
@Override
public boolean onTouchEvent(MotionEvent event) {
   //do something
}
 
@Override
protected void onDraw(Canvas canvas) {
    //Do something
    invalidate();
}

i have tried to implement admob with this code(among other):

public void ads() {
    adView = new AdView((Activity) getContext(), AdSize.BANNER,
             "xxxxxxxxxxx");

    LinearLayout.LayoutParams params;
    params = new LinearLayout.LayoutParams(
             LinearLayout.LayoutParams.FILL_PARENT,
             LinearLayout.LayoutParams.WRAP_CONTENT);

    // Create a linear layout
    LinearLayout layout = new LinearLayout((Activity) getContext());
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setPadding(6, 6, 6, 6);
    layout.addView(adView, params);
}

I searched hours for a solution but I can't find any.

Can somebody help me in the right direction?


Solution

  • First of all, your AdView need to be a part of your content view. The LinearLayout you created in your ads() function. Second, you need to create an AdRequest and load the ad with that request:

    AdRequest request = new AdRequest();
    request.addTestDevice(AdRequest.TEST_EMULATOR); // get test ads on emulator.
    adView.loadAd(request);
    

    Check out the documentation for more information on how to set up your AdView.