问题
I have a question about Navigation Drawer Header Section Items.
Actually I want to change a TextView in HeaderLayout programatically, here are codes:
drawer menu: <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="all">
<item
android:id="@+id/navItem1"
android:icon="@drawable/ic_home_drawer"
android:title="A"/>
<item
android:id="@+id/navItem2"
android:icon="@drawable/ic_gallery_drawer"
android:title="B"/>
<item
android:id="@+id/navItem3"
android:icon="@drawable/ic_exhibition"
android:title="C"/>
<item
android:id="@+id/navItem4"
android:icon="@drawable/ic_news_drawer"
android:title="D"/>
<item
android:id="@+id/navItem5"
android:icon="@drawable/ic_exit_drawer"
android:title="E"/>
</group>
here is Navigation Header XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="256dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/nav_header" />
<ImageView
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_gravity="bottom"
android:scaleType="centerCrop"
android:src="@drawable/nav_header_bar" />
<TextView
android:id="@+id/nav_title"
android:layout_width="match_parent"
android:layout_gravity="top"
android:gravity="center"
android:text="IAMTEXT"
android:layout_height="wrap_content" />
I wanna change this programatically: android:text="IAMTEXT"
回答1:
In your Java code:
- Use
findViewById(R.id.nav_title)
to find theTextView
- use
setText()
to set a text to theTextView
For example, in your MainActivity:
TextView navTitle = (TextView) findViewById(R.id.nav_title);
navTitle.setText("This is a changed string.");
回答2:
I am assuming you are using NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer_menu" />
ok. you can get the header view from the navigation view
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
View headView = navigationView.getHeaderView(0);
((TextView) headView.findViewById(R.id.nav_title)).setText("New title");
来源:https://stackoverflow.com/questions/32286109/change-design-support-navigation-view-header-title-programmatically