You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在第二个Activity的ScrollView顶部集成AdMob横幅广告?

解决ScrollView顶部添加AdMob横幅广告的问题

我来帮你搞定这个问题!你的代码里有几个关键问题导致广告无法正常显示,咱们一步步修正:

第一步:修正布局文件(activity_new.xml)

ScrollView只能包含一个直接子视图,所以你需要把AdView和你的TextView放在一个容器(比如LinearLayout)里,再把这个容器作为ScrollView的子View。这样广告就能固定在ScrollView的顶部,跟着内容一起滚动。

示例布局代码:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- AdMob横幅广告占位 -->
        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ads:adSize="BANNER"
            ads:adUnitId="你的广告单元ID" />

        <!-- 你的内容文本视图 -->
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp" />

    </LinearLayout>
</ScrollView>

第二步:修正Java代码中的错误

你原来的代码里犯了一个典型的逻辑错误:先new AdView(this)创建了广告视图对象,但紧接着又用findViewById(R.id.adView)覆盖了这个对象,导致之前设置的广告尺寸、单元ID全部失效。咱们直接获取布局里预先定义好的AdView再初始化即可:

修正后的Java代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);

    // 初始化AdMob SDK
    MobileAds.initialize(this, "你的App ID");

    // 获取布局中定义的AdView
    AdView adView = findViewById(R.id.adView);
    // 如果布局里没设置adSize和adUnitId,这里可以补充设置(二选一即可)
    // adView.setAdSize(AdSize.BANNER);
    // adView.setAdUnitId("你的广告单元ID");

    // 创建广告请求并加载广告
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    // 处理ActionBar和内容文本
    ActionBar actionBar = getSupportActionBar();
    TextView mDetailTv = findViewById(R.id.textView);
    Intent intent = getIntent();
    
    String mActionBarTitle = intent.getStringExtra("actionBarTitle");
    String mContext = intent.getStringExtra("contentTv");
    
    if (actionBar != null) {
        actionBar.setTitle(mActionBarTitle);
    }
    mDetailTv.setText(mContext);
}

额外注意事项

  • 记得把代码里的你的App ID和你的广告单元ID替换成你在AdMob后台获取的真实ID
  • 测试阶段建议使用AdMob官方提供的测试广告单元ID,避免触发真实广告的展示限制
  • 确保你的项目已经正确集成AdMob依赖(既然第一个Activity能正常显示广告,这一步应该没问题,但可以再核对一下)

内容的提问来源于stack exchange,提问作者Vish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:07:16