【发布时间】:2015-11-13 15:37:08
【问题描述】:
问题
其实我想以编程方式更改Navigation Drawer的HeaderLayout背景,
nav_header_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar_fr"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom"
android:id="@+id/header">
</LinearLayout>
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:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<include layout="@layout/app_bar_main" android:layout_width="match_parent"
android:layout_height="match_parent" />
<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:headerLayout="@layout/nav_header_main" app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
我尝试使用此代码更改标题背景:
LinearLayout header;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
header= (LinearLayout)findViewById(R.id.header);
header.setBackgroundResource(R.drawable.side_nav_bar_ru);
但显示错误
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.LinearLayout.setBackgroundResource(int)”
请大家帮帮我:(
【问题讨论】:
-
那个xml叫做activity_main.xml吗?因为如果您希望您的代码正常工作,它应该...
-
@Nanoc :是的,它被称为 :(
-
您的 findViewById 正在 activity_main.xml 中寻找“标题”,但它不存在,它在 nav_header_main.xml 中,这就是它返回 null 的原因,下面的答案是正确的,但我认为这不是一个有效的解决方案给你...
-
@Nanoc : 你不知道我的问题的解决方案吗?
-
将您的“标题”视图移动到其他 xml 或从正确的 xml 中获取它,这对您来说更容易。
标签: android navigation-drawer navigationbar navigationview android-navigationview