Android dynamic change Adview position
By Nethru Limited (www.nethru.com)
In this article, I will introduce how to dynamic change Adview position when using Admob in Android with Phonegap 2.9.0.
Open a terminal and create an new android project by below command
// <phonegap android create command> <project directory> <project package name> <project name> ./phonegap-2.9.0/lib/android/bin/create ./git/cordovaExample com.example.cordovaExample cordovaExample
There are 2 ways to use Phonegap with Android, the first is to extend DroidGap class.
public class cordovaExample extends DroidGap { ... }
The second is to implement CordovaInterface by our own.
public class cordovaExample extends Activity implements CordovaInterface { ... }
If we take a look at the source code DroidGap, we will find that DroidGap extend CordovaActivity and CordovaActivity is a class that implements CordovaInterface which contains hundreds of lines of code to initialize Phonegap plug-ins.
org.apache.cordova.DroidGap Source Code
org.apache.cordova.CordovaActivity Source Code
Therefore, in order to keep our code simple, we will keep extending DroidGap class and modify the default activity layout. The default activity layout in CordovaActivity is like the image below.
We expect that the layout is like the image below.
Here is the code to achieve this goal.
You can set different RelativeLayout.LayoutParams to change the position of adView.
public class cordovaExample extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize appView if (super.appView == null) { super.init(); } // Get the default layout and remove all components LinearLayout linearLayout = super.root; linearLayout.removeAllViews(); // Create a relativeLayout and add it to the linearLayout RelativeLayout.LayoutParams centerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); centerParams.addRule(RelativeLayout.CENTER_IN_PARENT); RelativeLayout relativeLayout = new RelativeLayout(this); relativeLayout.setLayoutParams(centerParams); linearLayout.addView(relativeLayout); // Add appView to the relativeLayout relativeLayout.addView(super.appView); // Add adView to the relativeLayout RelativeLayout.LayoutParams bottomParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); bottomParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); bottomParam.addRule(RelativeLayout.CENTER_HORIZONTAL); AdView adView = new AdView(this, AdSize.SMART_BANNER, "Your Admob ID"); adView.setLayoutParams(bottomParam); relativeLayout.addView(adView); // Finally, load appView URL super.loadUrl(Config.getStartUrl()); // Load Ads AdRequest adRequest = new AdRequest(); adView.loadAd(adRequest); } }