NavigationView获得/找到头布局布局、NavigationView

2023-09-12 06:37:12 作者:Ghost 幽灵

在我NavigationView我有身份证'的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 ...
});

使用新版本的Andr​​oid支持库,( 23.1.0 ),认为无法找到,返回null。随着previous版本,效果不错。它是一个错误还是我使用这个功能了?如果是这样,如何​​访问头布局,并添加行为呢?

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 (而不是previous 的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,并通过code加标题的优势。

This has the advantage of working on headers added via XML and via code.

如果你还在使用23.1.0,按相关的错误,你可以在充气code头,并使用 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.

 
精彩推荐
图片推荐