因此,我在 nav_header.xml 文件中为横幅广告容器添加了线性布局。我使用 LinearLayout 类在 MainActivity.java 文件中调用它。当我尝试启动它时应用程序崩溃并给出以下异常:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
指向我的 Main java 文件中的这一行:
// ADS section
mAdView = new AdView(this, "IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID", AdSize.BANNER_HEIGHT_90);
LinearLayout adContainer = (LinearLayout) findViewById(R.id.banner_container);
adContainer.addView(mAdView);
mAdView.loadAd();
我尝试对 adContainer 使用 Layout Infalter,但它失败了。这是我的 nav_header.xml 文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="@color/c1"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/banner_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
/>
</RelativeLayout>
</LinearLayout>
这是我的活动主文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="@+id/drawerLayout"
android:layout_height="match_parent">
<include layout="@layout/container_layout"/>
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header"
android:elevation="10dp"
app:menu="@menu/drawer_view"
tools:targetApi="lollipop" />
</androidx.drawerlayout.widget.DrawerLayout>