问题
实际上我想以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>
活动主.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)”
请有人帮助我:(