NavigationView 获取/查找标题布局 [英] NavigationView get/find header layout
问题描述
在我的 NavigationView 中,我有一个标题布局,id 为viewId",带有活动按钮.要设置这些按钮,我在活动的 onPostCreate
中执行以下操作:
In my NavigationView I have a header layout with id 'viewId' with active buttons. To setup those buttons, I do the following in activity's onPostCreate
:
final View panel = findViewById(R.id.viewId);
panel.setOnClickListener(new View.OnClickListener() {
... setup goes here ...
});
使用新版本的 android 支持库 (23.1.0),无法找到视图,返回 null.对于以前的版本,它运行良好.这是错误还是我使用此功能有误?如果是这样,如何访问标题布局并向其添加行为?
With new version android support library, (23.1.0), the view can't be found, it returns null. With previous versions it worked well. Is it a bug or am I using this feature wrong? If so, how to access header layout and add behavior to it?
推荐答案
23.1.0 版将 NavigationView
切换为使用 RecyclerView
(而不是之前的 ListView
) 并将标题添加为这些元素之一.这意味着它不能立即调用 findViewById()
- 在它附加到 NavigationView
之前需要一个布局传递.
Version 23.1.0 switches NavigationView
to using a RecyclerView
(rather than the previous ListView
) and the header is added as one of those elements. This means it is not instantly available to call findViewById()
- a layout pass is needed before it is attached to the NavigationView
.
对于版本 23.1.1 的支持库,您现在可以获得使用 getHeaderView()
引用标题视图:
For version 23.1.1 of the Support Library, you can now get a reference to the header view using getHeaderView()
:
View headerLayout = navigationView.getHeaderView(0); // 0-index header
这有利于处理通过 XML 和代码添加的标头.
This has the advantage of working on headers added via XML and via code.
如果您仍在使用 23.1.0,根据 相关错误,您可以在代码中扩展标题并在其上使用 findViewById()
:
If you are still using 23.1.0, as per the related bug, you can inflate the header in code and use findViewById()
on that:
View headerLayout =
navigationView.inflateHeaderView(R.layout.navigation_header);
panel = headerLayout.findViewById(R.id.viewId);
// panel won't be null
直到您移动到 23.1.1.
Until you move to 23.1.1.
这篇关于NavigationView 获取/查找标题布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!