如何在Android Fragment中创建按钮并实现点击展示广告
Fragment中创建按钮并实现点击展示广告的实现步骤
你当前编写的HomeFragment仅完成了布局inflate操作,未获取到布局View实例完成控件绑定,无法为按钮配置点击交互,完整实现流程如下:
步骤1:在布局文件中定义按钮控件
打开res/layout/fragment_home.xml,提前为两个按钮配置ID,后续Fragment才能通过ID关联对应的控件实例,示例布局片段:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <Button android:id="@+id/btn_interstitial" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="触发插屏广告展示"/> <Button android:id="@+id/btn_banner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="触发Banner广告展示"/> </LinearLayout>
步骤2:修改Fragment代码完成控件绑定
调整onCreateView方法的逻辑,不再直接返回inflate生成的布局对象,而是先将其存为局部变量,通过该变量绑定布局内的按钮、设置点击监听,最后再返回布局对象供Fragment渲染:
public class HomeFragment extends Fragment { Button interstitial; Button BannerAd; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 缓存inflate生成的根布局对象,作为后续控件查找的入口 View rootView = inflater.inflate(R.layout.fragment_home, container, false); // 通过根布局查找绑定对应ID的按钮实例 interstitial = rootView.findViewById(R.id.btn_interstitial); BannerAd = rootView.findViewById(R.id.btn_banner); // 为按钮设置点击事件监听 interstitial.setOnClickListener(view -> { // 此处填充插屏广告的展示逻辑 showInterstitialAd(); }); BannerAd.setOnClickListener(view -> { // 此处填充Banner广告的展示逻辑 showBannerAd(); }); return rootView; } // 抽离封装插屏广告展示逻辑 private void showInterstitialAd() { // 在此替换为实际广告SDK的调用代码,建议先判断广告加载状态再执行展示 } // 抽离封装Banner广告展示逻辑 private void showBannerAd() { // 在此替换为实际广告SDK的调用代码 } }
注意事项
- 不要在Fragment中直接调用
findViewById获取控件,该方法属于Activity的能力,Fragment必须通过自己inflate生成的根布局对象调用,否则会触发空指针崩溃 - 广告资源的预加载逻辑建议放在Fragment的初始化流程中完成,不要等用户点击按钮时才发起广告请求,避免出现点击后长时间等待广告加载的糟糕体验
- 调用广告展示方法前必须做非空、加载状态的校验,广告加载失败时直接给用户兜底反馈,不要无校验直接调用广告的show方法导致程序崩溃
内容的提问来源于stack exchange,提问作者Buddy
相关产品推荐
相关产品推荐

