How can I create a view and set attributes in Android through Code?

494 Views Asked by At

Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="fill_parent" android:layout_height="wrap_content">
    <com.mopub.mobileads.MoPubView
        android:id="@+id/adview"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        />

</RelativeLayout>

I am integrating MoPub SDK into my libGDX game and in MoPub documentation they are saying to create the MopubView in layout.xml like shown above. And then, do the following:

moPubView = (MoPubView) findViewById(R.id.adview);
moPubView.setAdUnitId("xxxxxxxxxxx"); // Enter your Ad Unit ID from www.mopub.com
moPubView.loadAd();
RelativeLayout layout = new RelativeLayout(this);

// Create the libgdx View
View gameView = initializeForView(new TBGame(this), config);

// Add the libgdx view
layout.addView(gameView);
layout.addView(moPubView)

setContentView(layout);

But libGDX won't load my xml file as it doesn't need it, resulting in null pointer exception whenever the execution reaches the above line. So the solution seems to be creating the view from code? How can I do that? A very similar question is here Integrating Mopub ads into Cocos2dx 2.1 but the solution stated there is NOT valid for the latest MoPub SDK.

Edit: This is the MoPubView class https://github.com/mopub/mopub-android-sdk/blob/master/mopub-sdk/src/main/java/com/mopub/mobileads/MoPubView.java

Attachment: Part of stack trace attached here: Stacktrace

2

There are 2 best solutions below

2
On

if your call to findViewById is in an activity, you need to call setContentView with layout in onCreate : setContentView(R.layout.layout); (btw, try a more descriptive name)

otherwise - to load dynamically look there : How to load layout in code from xml file and just use the resulting view as you wish, probably something like view.findViewById

3
On

you need to do something like this :

    setContentView(relativeLayout);
    RelativeLayout relativeLayout = new RelativeLayout(this);
    relativeLayout.addView(yourchildView);