有什么方法可以控制 NavigationView header 内的视图吗?

Is there any way to control views inside NavigationView header?

正如标题所说,我想知道NavigationViewheader里面有没有办法控制视图? (添加或删除 header 除外。)

例如:在header中,我有一个用户头像。默认情况下,它显示访客图像,但用户登录后,将显示真实头像。

如何实现?

因为我不能接受评论作为答案。所以,我在这里转贴 Moinkhan 的回答:

先创建headerXML喜欢lay_header.xml

<TextView
    android:id="@+id/tvThought"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

在您的 java 文件中,在 TextView 中将其膨胀到 header 以上。喜欢

TextView headerView = (TextView) LayoutInflater.from(this).inflate(R.layout.lay_header, null);
headerView.setText("Your_thoght");

现在将其添加为 HeaderView

navView = (NavigationView) findViewById(R.id.navView);
navView.addHeaderView(headerView);

就是这样...

您也可以在以下位置查看:Customising NavigationView - Adding dynamic headerView, Android Support Design Library

非常感谢! 同样,我们需要一个允许用户接受评论作为答案的功能!

只需尝试在 activity 中找到您的视图:

tvUserName = (TextView) findViewById(R.id.tv_username);

对我有用。我的页眉布局是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="?attr/colorPrimaryDark"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:orientation="vertical"
    android:gravity="bottom">

    <TextView
        android:id="@+id/tv_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

</LinearLayout>

我在 Activity 布局中的 NavigationView 是:

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_height="match_parent"
    android:layout_width="wrap_content"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/menu_drawer"/>

顺便说一句,我在给 LinearLayout 充气时遇到了问题,其中没有提供布局参数:

TextView headerView = (TextView) LayoutInflater.from(this).inflate(R.layout.lay_header, null);
headerView.setText("Your_thoght");

希望对您有所帮助。

另一种方法是使用 NavigationView 对象的方法 "inflateHeaderView()",如下所示(使用 "setContentView()" 后):

View headerLayout = navigationView.inflateHeaderView(R.layout.yours_nav_header_layout);

在此之后,您可以使用 "headerLayout" 访问页眉布局中的自定义视图,如下所示:

View cutomView = (TextView) headerLayout.findViewById(R.id.lay_sign_in);

在我的例子中,我使用 ButterKnife 框架来注入视图 "navigationView",如下所示:

@Bind(R.id.nav_view) NavigationView navigationView;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

将您的支持库更新到版本 23.1.1 或更高版本后,

你可以这样做 -

View header = navigationView.getHeaderView(0);
TextView text = (TextView) header.findViewById(R.id.textView);

或者如果您有多个 headers

navigationView.getHeaderCount()

参考:https://code.google.com/p/android/issues/detail?id=190226#c31