我需要更改导航标题上的背景颜色,当我在MainActivity中找到ViewById()时,会得到null。
这是导航标题,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/nav_second_header_bg"
android:layout_width="match_parent"
android:layout_height="100dp"
xmlns:tools="http://schemas.android.com/tools"
android:background="#00aeef"
android:gravity="bottom"
android:orientation="vertical"
android:padding="12dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
tools:context=".MainActivity">
<ImageView
android:id="@+id/school"
android:layout_width="wrap_content"
android:layout_height="88dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/schatkamer" />
<TextView
android:id="@+id/nav_second_header_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/school"
android:layout_marginEnd="15dp"
android:layout_toStartOf="@+id/school"
android:text="account name"
android:layout_marginRight="15dp"
android:layout_toLeftOf="@+id/school" />
</RelativeLayout>
这是onCreate MainActivity中的代码
second_bar_header = findViewById(R.id.nav_second_header_bg); //this id returns null
second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));
TextView tv = findViewById(R.id.nav_second_header_text); // this is null
tv.setText("hi");
答案 0 :(得分:0)
您应该尝试这样的事情
NavigationView navigationView = findViewById(R.id.you_nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
TextView username = header.findViewById(R.id.nav_second_header_text);
username.setText("Hi");
second_bar_header = header.findViewById(R.id.nav_second_header_bg);
second_bar_header.setBackgroundColor(Color.parseColor("00ff00"));