1

Mopub 集成说明建议使用如下代码段在 xml 中创建广告视图:

<com.mopub.mobileads.MoPubView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/adview"
android:layout_width="fill_parent"
android:layout_height="50dp"
/> 

然后说明建议在活动的 create 方法中创建广告视图,如下所示:

moPubView = (MoPubView)findViewById(R.id.adview);
moPubView.setAdUnitId("123412341234");
moPubView.loadAd();

遗憾moPubView的是没有创建,因为 Cocos2dx 2.1 不再使用 XML 进行布局。因此,由于空指针异常,应用程序在启动时崩溃。

在尝试创建广告视图之前,我尝试传递R.layout.main给。setContentView这确实成功地创建了广告视图,但是应用程序的其余部分不可见。

如何在不使用 XML 的情况下以编程方式创建类似于上述视图的视图?

我认为这解决了空指针异常问题,而无需调用setContentView.

4

1 回答 1

4
private static BannerAdManager m_adDelegate = null;
private static FrameLayout.LayoutParams m_bannerParam = null;
private static FrameLayout m_appLayout = null;


public static void initialize(Activity p_activity)
{
    // create instance of delegate
    if( m_adDelegate == null )
    {
        m_adDelegate = new BannerAdManager();
    }

    m_activity = p_activity;


    //~~~setup mopub banner ad
    //~~~create mopub ad view
    m_mopubView = new MoPubView(m_activity);

    m_bannerParam = new FrameLayout.LayoutParams(   
                        FrameLayout.LayoutParams.WRAP_CONTENT,
                        FrameLayout.LayoutParams.WRAP_CONTENT
                    );

    m_mopubView.setAdUnitId(Config_Android._ID);
    m_mopubView.setBannerAdListener(m_adDelegate);
    m_mopubView.loadAd();

    //get current layout
    m_appLayout = (FrameLayout) m_activity.findViewById(android.R.id.content);

    // set default alignment
    m_bannerParam.gravity = Gravity.TOP | Gravity.CENTER;

    //add mopub view to layout
    m_appLayout.addView(m_mopubView, m_bannerParam);

}

    public static void setBannerPositionTopWithPadding(float p_padding)
    {
        getActivity().runOnUiThread(new Runnable() 
        {
            public void run()
            {
                activity = getActivity();

                m_bannerParam.gravity  = Gravity.TOP | Gravity.CENTER;
                m_bannerParam.width    = FrameLayout.LayoutParams.WRAP_CONTENT;
                m_bannerParam.height   = FrameLayout.LayoutParams.WRAP_CONTENT;

                m_bannerParam.topMargin = (int) p_padding;

                m_appLayout.updateViewLayout(m_mopubView, m_bannerParam);
                m_mopubView.refreshDrawableState();

            }
        });
    }
于 2013-08-16T07:09:52.577 回答