简体   繁体   中英

All Views (Image, Text, etc.) return null from findViewById() from mainActivity

I am trying to assign dailyImage in nav_header.xml from MainActivity class.

MainActivity class has setContentView(R.layout.activity_main);

I'm able to assign Views in nav_action.xml, but not in nav_header.xml.
I can't seem to figure why findViewById() is returning null when trying to access DailyImage in nav_header.xml from MainActivity class.

Keeping like that, is there a way I can assign

nav_header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="@android:color/holo_blue_dark"
android:padding="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
tools:context="com.example.hello.world.MainActivity">

<ImageView
    android:id="@+id/DailyImage"
    android:layout_width="match_parent"
    android:layout_height="108dp"
    android:layout_below="@+id/menu_text"
    android:layout_alignParentStart="true" />
</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/nav_drawer_main"
android:background="@color/gray"
android:orientation="vertical"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/nav_action"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:layout_width="260dp"
    android:layout_height="match_parent"
    android:id="@+id/nav_men"
    android:background="@color/black"
    app:menu="@menu/nav_menu"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header"
    app:itemIconTint="@drawable/drawer_item"
    app:itemTextColor="@drawable/drawer_item">
</android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

The header is not part of the Activity root layout, so it cannot traverse all nested views to find it, and so it is null.

You must go through the NavigationView.

NavigationView get/find header layout

Is there any way to control views inside NavigationView header?

// Shouldn't be null
NavigationView navView = (NavigationView) findViewById(R.id.nav_men); 
View headerView = navView.getHeaderView(0);

// This is the ImageView
ImageView iv = (ImageView) headerView.findViewById(R.id.DailyImage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM