Easy and reusable ItemDecoration
WithStatic headers can easily be added with an ItemDecoration you can easily and without any further changes. in your code add static views to the top of your list:
// add the decoration. done. HeaderDecoration headerDecoration = new HeaderDecoration(/* init */); recyclerView.addItemDecoration(headerDecoration); You can reuse theThe decoration is also reusable since there is no need to modify the adapter or the RecyclerView at all.
The downsides The sample code provided below will require a view to this solution are that, as ofadd to the current state, there is no possibility for user interaction - youtop which can not set a ClickListener. Also, since this is an ItemDecoration, you have to have at least one element in your list or it will not showjust be inflated like everything else. You could reuse the layout for an empty state or provide an empty dummy item when your dataset is empty to fixIt can look like this issue.:
Attached is the source code to the above demonstrated decoration. By measuring and drawing the View you can pass most layouts into the decoration and it will render nicely on top of your list, only wrap_content and match_parent might not behave as expected.
Why static?
If you just have to display text and images this solution is for you—there is no possibility for user interaction like buttons or view pagers, since it will just be drawn to top of your list.
Empty list handling
If there is no view to decorate, the decoration will not be drawn. You will still have to handle an empty list yourself. (One possible workaround would be to add a dummy item to the adapter.)
The code
You can find the full source code here on GitHub including a Builder to help with the initialization of the decorator, or just use the code below and supply your own values to the constructor.
Please be sure to set a correct layout_height for your view. e.g. match_parent might not work properly.
Please note: The GitHub project is my personal playground. It is not thorougly tested, which is why there is no library yet.
What does it do?
An ItemDecoration is additional drawing to an item of a list. In this case, a decoration is drawn to the top of the first item.
The view gets measured and laid out, then it is drawn to the top of the first item. If a parallax effect is added it will also be clipped to the correct bounds.