修改布局中没有 class 的 textview

Modify textview in layout that doesn't have class

我使用的是最新的 android 抽屉式导航栏。但是我对 header 有一些问题,我想动态地改变它。我怎样才能做到这一点?我可以修改 header 布局中已用于 header 导航视图中的文本视图吗?

Can i modify the textview in header layout that has been used for header in navigationview?

是的!你可以!

我假设您使用的是 NavigationView,像这样:

   <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_home"
        app:menu="@menu/activity_home_drawer" />

让我们假设 nav_header_home 是这样的:

<?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"
    android:gravity="bottom"
    android:orientation="vertical"
    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">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:id="@+id/mainText"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/subText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

现在更改 mainTextsubText。您在 Activity 中所要做的就是 findViewById 并根据需要进行修改。例如:

 protected void onCreate(Bundle savedInstanceState) {
    //// Your initiation code
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    View hView =  navigationView.getHeaderView(0);
    TextView mainText = (TextView)hView.findViewById(R.id.mainText);
    mainText.setText("Hello World!");
}