代码之家  ›  专栏  ›  技术社区  ›  rated2016

所有视图(图像、文本等)从mainActivity的findViewById()返回null

  •  0
  • rated2016  · 技术社区  · 7 年前

    我正在尝试分配dailyImage nav_header.xml MainActivity

    setContentView(R.layout.activity_main);

    我能够在nav\U操作中分配视图。xml,但不在nav_header.xml中。

    保持这样,有什么方法可以分配吗

    nav\u 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>
    

    <?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>
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   OneCricketeer Gabriele Mariotti    7 年前

    您必须浏览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);