3

因此,我在 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>
4

1 回答 1

1

NullPointerException发生是因为banner_container它不是activity_mainXML 的一部分。它是nav_headerXML 的一部分,活动层次结构不容易访问。

要访问导航标题:

View headerView = ((NavigationView)findViewById(R.id.nav_view)).getHeaderView(0);
LinearLayout container = (LinearLayout) headerView.findViewById(R.id.banner_container);

我希望这有帮助!!

编辑:铸造 NavigationView

于 2020-11-27T06:30:36.077 回答