使用代码中的属性创建Android xml元素

时间:2019-07-12 09:55:40

标签: android android-linearlayout adview

我想在代码中动态创建一个xml元素,但前提是该元素尚不存在。

这是我要创建的元素的xml。 (注意,我不会在xml中声明它,这是我要在代码中创建的元素的xml)

<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"/>

这是正确的检查,以查看是否已经存在吗?

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
}

我又如何将其添加到LinearLayout的底部?

1 个答案:

答案 0 :(得分:1)

首先,您无需检查条件运行时,就可以直接即时创建

这是根据条件在运行时添加视图的更好方法

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);

完全取决于您的情况来定制事物。