androidandroid-linearlayoutadview

Creating Android xml Element with properties in Code


I want to create an xml element in code on the fly, but only if it is not already there.

This is the xml of the element I want to create. (Note, I will not be declaring this in xml, this is the xml of the element I want to create in code):

<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#000000"
android:paddingTop="5dp"
app:adSize="SMART_BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111"/>

Is this the correct check to see if it already there?

AdView adView;
if((adView = (AdView) m_Context.findViewById(R.id.adView)) != null){
    // It is already there
}else{
    // It is not there, create it on the fly
}

Also how do I add it to the bottom of a LinearLayout?


Solution

  • Firstly, you don't need to check the condition run-time you can directly create on-the-fly.

    This is better way to add view on run-time based on condition

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    
             AdView mAdView = new AdView(this);
             mAdView.setAdSize(AdSize.SMART_BANNER);
             mAdView.setAdUnitId("xxxx-xxxx-xxxx-xxxx");
    
    
             AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
             adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
             layout.addView(mAdView);
             mAdView.loadAd(adRequestBuilder.build());
             setContentView(layout);
    

    It's totally depends on your condition to customize the thing around.