问题
实际上我想以编程方式更改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)'
有人请帮助我:(
答案 0 :(得分:2)
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.getHeaderView(0).findViewById(R.id.header).setBackgroundResource(R.drawable.side_nav_bar_ru);
答案 1 :(得分:0)
我认为你应该改变
setContentView(R.layout.activity_main);
到
setContentView(R.layout.nav_header_main);