我的TextView
标记内有一个NavigationView
。但是我无法通过findViewById
方法获得它:
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:itemIconTint="@color/drawer_item"
app:itemTextColor="@color/drawer_item"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/version_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp" />
</RelativeLayout>
</android.support.design.widget.NavigationView>
我尝试了以下方法,但我总是得到null
。
findViewById(R.id.version_name); //null
navigationView.findViewById(R.id.version_name); //null
navigationView.getRootView.findViewById(R.id.version_name); //null
答案 0 :(得分:2)
我确实有同样的问题..
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_main, null);
navigationView.addHeaderView(header);
TextView text = (TextView) header.findViewById(R.id.textView);
texto.setText("Your text");
答案 1 :(得分:1)
我想要做的是为我的导航抽屉添加一个泡沫以显示应用版本。由于应用版本是动态数据,因此将静态文本视图添加到导航视图下方并使用外部布局包装它们也无法正常工作。解决问题的正确方法如下所述:
主要思想是在NavigationView中放置两个NavigationView:一个用于普通导航项目,另一个用于起泡项目。
<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:id="@+id/layout_dashboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<!-- Activity content goes here -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation_drawer_container"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
<android.support.design.widget.NavigationView
android:id="@+id/navigation_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="top"
app:menu="@menu/menu_navigation_drawer" />
<android.support.design.widget.NavigationView
android:id="@+id/navigation_drawer_bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:menu="@menu/menu_navigation_drawer_bottom" />
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>