Android导航视图中的标题重复问题

4

我在我的应用程序中使用了导航视图。导航视图中的标题重复出现了两次,但实际上我已经在xml中删除了它(app:headerLayout="@layout/header")。我想要从导航视图的标题实现操作(例如按钮)。

在代码中,我像这样编写:

    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
    headerView = mNavigationView.inflateHeaderView(R.layout.bp_header);
    googele_plus = (ImageButton) headerView.findViewById(R.id.google_p);
    facebook = (ImageButton) headerViewfindViewById(R.id.fb);

头部如下所示

Header repetition

如果从图像按钮中删除headerView,则会出现NullPointerException错误 任何建议或解决方案将不胜感激

6个回答

3

请将您的支持库更新至23.1.1或更高版本。

之后,您可以执行以下操作 -

在NavigationView中添加headerview:app:headerLayout="@layout/header"。

然后,您可以通过以下方式访问它:

    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
    View headerView = mNavigationView.getHeaderView(0)

    googele_plus = (ImageButton) headerView.findViewById(R.id.google_p);
    facebook = (ImageButton) headerView.findViewById(R.id.fb);

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

2
    You may have header layout in xml and also you are adding header from java like 

    headerView = mNavigationView.inflateHeaderView(R.layout.bp_header);

    So just remove above line from java and add it through the xml
    You can add following in your xml       

 <include
 android:id="@+id/header"
 layout="@layout/navigation_header" />

     and then in java create ref like below          



      googele_plus = (ImageButton) findViewById(R.id.google_p);
         facebook = (ImageButton) findViewById(R.id.fb);

     Clean and Build the project and then run 

1

我在使用NavigationView头部时遇到了NPE,因为我在布局中添加了头部app:headerLayout="@layout/header"

为了摆脱这个NPE,我开始像下面这样以编程方式添加头部

View header = LayoutInflater.from(this).inflate(R.layout.bp_header, null);
mNavigationView.addHeaderView(header);
googele_plus = (ImageButton) header.findViewById(R.id.google_p);

1
看起来你创建了两个标题。我也遇到了同样的问题。
 headerView = mNavigationView.inflateHeaderView(R.layout.bp_header);

这行代码^实际上是在运行时创建了新的视图。我相信你已经在XML中创建了同样的标题。尝试从XML中删除headerView,这将解决你的问题。


0

你可能会发现导航视图头部设置函数被调用了两次,因此它被创建了两次。

如果你在 onStart() 方法中编写了设置导航头部视图的代码,请将其删除并编写到 onCreate() 方法中。

如果你去其他活动并返回,onStart() 方法将被多次调用。因此,它会创建多个头部。或者检查你的代码是否多次调用了该代码。


0
在KOTLIN中,我使用以下代码实现了。
步骤1. 从NavigationView中删除“app:headerLayout = "@layout/your_header_layout"”。
步骤2. 在您的活动中添加以下代码。
var nav = nav_view.inflateHeaderView(R.layout.nav_header_home)
nav?.nav_header_title?.text = "Your text "

注意:如果您不从NavigationView中删除app:headerLayout,则标题将重复两次。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接