我对导航抽屉标题部分项目有疑问 实际上我想以编程方式更改HeaderLayout中的TextView,这里是代码:
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>
这是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" />
我想以编程方式更改此内容:android:text="IAMTEXT"
答案 0 :(得分:3)
我假设您正在使用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" />
确定。您可以从导航视图中获取标题视图
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
View headView = navigationView.getHeaderView(0);
((TextView) headView.findViewById(R.id.nav_title)).setText("New title");
答案 1 :(得分:1)
在您的Java代码中:
findViewById(R.id.nav_title)
查找TextView
setText()
将文字设置为TextView
例如,在您的MainActivity中:
TextView navTitle = (TextView) findViewById(R.id.nav_title);
navTitle.setText("This is a changed string.");