├── .github └── workflows │ └── android.yml ├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── yuyang │ │ └── stickyheaders │ │ └── demo │ │ ├── MainActivity.java │ │ ├── RecyclerAdapter.java │ │ └── model │ │ ├── HeaderItem.java │ │ └── Item.java │ └── res │ ├── layout │ ├── activity_main.xml │ ├── header_view.xml │ └── item_view.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── art ├── screenshot.gif └── screenshot.mp4 ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── stickyheaders ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main ├── AndroidManifest.xml └── java └── com └── yuyang └── stickyheaders ├── AdapterDataProvider.java ├── StickyHeaderModel.java ├── StickyLinearLayoutManager.java └── handler ├── StickyHeaderHandler.java └── ViewHolderFactory.java /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - name: set up JDK 1.8 13 | uses: actions/setup-java@v1 14 | with: 15 | java-version: 1.8 16 | - name: Run unit tests 17 | run: ./gradlew test 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | /.idea/ 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2019 smuyyh. All right reserved. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StickyHeaderRecyclerView ![](https://img.shields.io/github/v/release/smuyyh/StickyHeaderRecyclerView.svg) [![GitHub license](https://img.shields.io/github/license/smuyyh/StickyHeaderRecyclerView)](https://github.com/smuyyh/StickyHeaderRecyclerView/blob/master/LICENSE) 2 | 3 | RecyclerView 悬浮吸顶 Header,支持点击事件与状态绑定 4 | 5 | 6 | 7 | ## 依赖 8 | 9 | ``` 10 | buildscript { 11 | repositories { 12 | ... 13 | maven { url "https://jitpack.io" } 14 | } 15 | dependencies { 16 | ... 17 | } 18 | } 19 | ``` 20 | 21 | ``` 22 | dependencies { 23 | implementation 'com.github.smuyyh:StickyHeaderRecyclerView:1.1.0' 24 | } 25 | ``` 26 | 27 | ## 用法 28 | 29 | #### 1. Header Model 30 | 31 | Header Model 需要实现 ```StickyHeaderModel``` 接口 32 | 33 | ```java 34 | public class HeaderItem implements StickyHeaderModel { 35 | 36 | public final String title; 37 | 38 | /** 39 | * 状态保存示例,如果header存在一些交互性行为,在onBindViewHolder里面需要绑定悬浮header的状态 40 | */ 41 | public int color = 0xff777777; 42 | 43 | public HeaderItem(String title) { 44 | this.title = title; 45 | } 46 | } 47 | 48 | public class Item { 49 | 50 | public final String title; 51 | public final String message; 52 | 53 | public Item(String title, String message) { 54 | this.title = title; 55 | this.message = message; 56 | } 57 | } 58 | ``` 59 | 60 | #### 2. Adapter 61 | 62 | RecyclerView Adapter 需要实现 ```AdapterDataProvider``` 接口,并在 ```getAdapterData()``` 返回 model 数据,用于判断对应 position 是否为 Header 63 | 64 | ```java 65 | public final class RecyclerAdapter extends RecyclerView.Adapter implements AdapterDataProvider { 66 | 67 | private final List dataList = new ArrayList<>(); 68 | 69 | @Override 70 | public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 71 | if (viewType == 0) { 72 | return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false)); 73 | } else { 74 | return new HeaderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.header_view, parent, false)); 75 | } 76 | } 77 | 78 | @Override 79 | public void onBindViewHolder(final BaseViewHolder holder, final int position) { 80 | 81 | } 82 | 83 | @Override 84 | public int getItemCount() { 85 | return dataList.size(); 86 | } 87 | 88 | @Override 89 | public int getItemViewType(int position) { 90 | return dataList.get(position) instanceof Item ? 0 : 1; 91 | } 92 | 93 | @Override 94 | public List getAdapterData() { 95 | return dataList; 96 | } 97 | 98 | private static final class ItemViewHolder extends BaseViewHolder { 99 | 100 | TextView titleTextView; 101 | TextView messageTextView; 102 | 103 | ItemViewHolder(View itemView) { 104 | super(itemView); 105 | 106 | titleTextView = itemView.findViewById(R.id.tv_title); 107 | messageTextView = itemView.findViewById(R.id.tv_message); 108 | } 109 | } 110 | 111 | private static final class HeaderViewHolder extends BaseViewHolder { 112 | 113 | TextView titleTextView; 114 | TextView button; 115 | 116 | HeaderViewHolder(View itemView) { 117 | super(itemView); 118 | 119 | titleTextView = itemView.findViewById(R.id.tv_title); 120 | button = itemView.findViewById(R.id.button); 121 | } 122 | } 123 | 124 | static class BaseViewHolder extends RecyclerView.ViewHolder { 125 | 126 | BaseViewHolder(View itemView) { 127 | super(itemView); 128 | } 129 | } 130 | } 131 | ``` 132 | 133 | #### 3. Setup 134 | 135 | ```java 136 | RecyclerView recyclerView = findViewById(R.id.recycler_view); 137 | recyclerView.setLayoutManager(new StickyLinearLayoutManager(this, adapter)); // StickyLinearLayoutManager 替代 LinearLayoutManager 138 | 139 | RecyclerAdapter adapter = new RecyclerAdapter(); 140 | adapter.setDataList(genDataList(0)); 141 | recyclerView.setAdapter(adapter); 142 | ``` 143 | 144 | #### 4. Features 145 | 146 | **(4.1) Header Attach Listener** 147 | 148 | ```java 149 | stickyLinearLayoutManager.setStickyHeaderListener(new StickyLinearLayoutManager.StickyHeaderListener() { 150 | @Override 151 | public void headerAttached(View headerView, int adapterPosition) { 152 | Log.d("StickyHeaderRecyclerView", "Header Attached : " + adapterPosition); 153 | } 154 | 155 | @Override 156 | public void headerDetached(View headerView, int adapterPosition) { 157 | Log.d("StickyHeaderRecyclerView", "Header Detached : " + adapterPosition); 158 | } 159 | }); 160 | ``` 161 | 162 | **(4.2) Elevation** 163 | 164 | ```java 165 | layoutManager.elevateHeaders(true); // default value : 5dp 166 | 167 | // or 168 | layoutManager.elevateHeaders(dpValue); 169 | ``` 170 | 171 | Thanks: [StickyHeaders](https://github.com/bgogetap/StickyHeaders) 172 | 173 | ## LICENSE 174 | 175 | ``` 176 | Copyright (c) 2019 smuyyh. All right reserved. 177 | 178 | Licensed under the Apache License, Version 2.0 (the "License"); 179 | you may not use this file except in compliance with the License. 180 | You may obtain a copy of the License at 181 | 182 | http://www.apache.org/licenses/LICENSE-2.0 183 | 184 | Unless required by applicable law or agreed to in writing, software 185 | distributed under the License is distributed on an "AS IS" BASIS, 186 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 187 | See the License for the specific language governing permissions and 188 | limitations under the License. 189 | ``` 190 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | 6 | defaultConfig { 7 | applicationId "com.yuyang.sticky" 8 | minSdkVersion 15 9 | targetSdkVersion 28 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | 20 | lintOptions { 21 | abortOnError false 22 | } 23 | 24 | } 25 | 26 | dependencies { 27 | implementation 'com.github.smuyyh:StickyHeaderRecyclerView:1.1.0' 28 | compile 'com.android.support:appcompat-v7:28.0.0' 29 | compile("com.android.support:recyclerview-v7:28.0.0") 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/bgogetap/Desktop/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/stickyheaders/demo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.demo; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.support.v7.widget.LinearSmoothScroller; 8 | import android.support.v7.widget.RecyclerView; 9 | import android.util.Log; 10 | import android.view.View; 11 | 12 | import com.yuyang.stickyheaders.StickyLinearLayoutManager; 13 | import com.yuyang.stickyheaders.demo.model.HeaderItem; 14 | import com.yuyang.stickyheaders.demo.model.Item; 15 | 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | public class MainActivity extends AppCompatActivity { 20 | 21 | private RecyclerView recyclerView; 22 | 23 | private RecyclerAdapter adapter; 24 | 25 | @Override 26 | protected void onCreate(Bundle savedInstanceState) { 27 | super.onCreate(savedInstanceState); 28 | setContentView(R.layout.activity_main); 29 | 30 | recyclerView = findViewById(R.id.recycler_view); 31 | 32 | adapter = new RecyclerAdapter(); 33 | adapter.setDataList(genDataList(0)); 34 | StickyLinearLayoutManager layoutManager = new StickyLinearLayoutManager(this, adapter) { 35 | @Override 36 | public boolean isAutoMeasureEnabled() { 37 | return true; 38 | } 39 | 40 | @Override 41 | public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { 42 | RecyclerView.SmoothScroller smoothScroller = new TopSmoothScroller(recyclerView.getContext()); 43 | smoothScroller.setTargetPosition(position); 44 | startSmoothScroll(smoothScroller); 45 | } 46 | 47 | class TopSmoothScroller extends LinearSmoothScroller { 48 | 49 | TopSmoothScroller(Context context) { 50 | super(context); 51 | } 52 | 53 | @Override 54 | public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) { 55 | return boxStart - viewStart; 56 | } 57 | } 58 | }; 59 | layoutManager.elevateHeaders(5); 60 | recyclerView.setLayoutManager(layoutManager); 61 | recyclerView.setAdapter(adapter); 62 | layoutManager.setStickyHeaderListener(new StickyLinearLayoutManager.StickyHeaderListener() { 63 | @Override 64 | public void headerAttached(View headerView, int adapterPosition) { 65 | Log.d("StickyHeader", "Header Attached : " + adapterPosition); 66 | } 67 | 68 | @Override 69 | public void headerDetached(View headerView, int adapterPosition) { 70 | Log.d("StickyHeader", "Header Detached : " + adapterPosition); 71 | } 72 | }); 73 | 74 | recyclerView.postDelayed(new Runnable() { 75 | @Override 76 | public void run() { 77 | adapter.addDataList(genDataList(adapter.getItemCount())); 78 | } 79 | }, 5000); 80 | } 81 | 82 | public static List genDataList(int start) { 83 | List items = new ArrayList<>(); 84 | for (int i = start; i < 100 + start; i++) { 85 | if (i % 10 == 0) { 86 | items.add(new HeaderItem("Header " + i)); 87 | } else { 88 | items.add(new Item("Item " + i, "description " + i)); 89 | } 90 | } 91 | return items; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/stickyheaders/demo/RecyclerAdapter.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.demo; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.LayoutInflater; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.widget.TextView; 8 | 9 | import com.yuyang.stickyheaders.AdapterDataProvider; 10 | import com.yuyang.stickyheaders.demo.model.HeaderItem; 11 | import com.yuyang.stickyheaders.demo.model.Item; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | public final class RecyclerAdapter extends RecyclerView.Adapter implements AdapterDataProvider { 17 | 18 | private final List dataList = new ArrayList<>(); 19 | 20 | @Override 21 | public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 22 | if (viewType == 0) { 23 | return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false)); 24 | } else { 25 | return new HeaderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.header_view, parent, false)); 26 | } 27 | } 28 | 29 | @Override 30 | public void onBindViewHolder(final BaseViewHolder holder, final int position) { 31 | final Object item = dataList.get(position); 32 | if (item instanceof Item) { 33 | ItemViewHolder itemViewHolder = (ItemViewHolder) holder; 34 | itemViewHolder.titleTextView.setText(((Item) item).title); 35 | itemViewHolder.messageTextView.setText(((Item) item).message); 36 | } else if (item instanceof HeaderItem) { 37 | HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder; 38 | headerViewHolder.titleTextView.setText(((HeaderItem) item).title); 39 | 40 | headerViewHolder.button.setTextColor(((HeaderItem) item).color); 41 | headerViewHolder.button.setOnClickListener(new View.OnClickListener() { 42 | @Override 43 | public void onClick(View v) { 44 | if (((HeaderItem) item).color == 0xffff5050) { 45 | ((HeaderItem) item).color = 0xff777777; 46 | } else { 47 | ((HeaderItem) item).color = 0xffff5050; 48 | } 49 | 50 | notifyItemChanged(position); 51 | } 52 | }); 53 | } 54 | } 55 | 56 | @Override 57 | public int getItemCount() { 58 | return dataList.size(); 59 | } 60 | 61 | @Override 62 | public int getItemViewType(int position) { 63 | return dataList.get(position) instanceof Item ? 0 : 1; 64 | } 65 | 66 | @Override 67 | public List getAdapterData() { 68 | return dataList; 69 | } 70 | 71 | public void setDataList(List items) { 72 | dataList.clear(); 73 | dataList.addAll(items); 74 | notifyDataSetChanged(); 75 | } 76 | 77 | public void addDataList(List items) { 78 | if (items != null) { 79 | int start = dataList.size(); 80 | dataList.addAll(items); 81 | notifyItemRangeInserted(start, items.size()); 82 | } 83 | } 84 | 85 | private static final class ItemViewHolder extends BaseViewHolder { 86 | 87 | TextView titleTextView; 88 | TextView messageTextView; 89 | 90 | ItemViewHolder(View itemView) { 91 | super(itemView); 92 | 93 | titleTextView = itemView.findViewById(R.id.tv_title); 94 | messageTextView = itemView.findViewById(R.id.tv_message); 95 | } 96 | } 97 | 98 | private static final class HeaderViewHolder extends BaseViewHolder { 99 | 100 | TextView titleTextView; 101 | TextView button; 102 | 103 | HeaderViewHolder(View itemView) { 104 | super(itemView); 105 | 106 | titleTextView = itemView.findViewById(R.id.tv_title); 107 | button = itemView.findViewById(R.id.button); 108 | } 109 | } 110 | 111 | static class BaseViewHolder extends RecyclerView.ViewHolder { 112 | 113 | BaseViewHolder(View itemView) { 114 | super(itemView); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/stickyheaders/demo/model/HeaderItem.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.demo.model; 2 | 3 | import com.yuyang.stickyheaders.StickyHeaderModel; 4 | 5 | public class HeaderItem implements StickyHeaderModel { 6 | 7 | public final String title; 8 | 9 | /** 10 | * 状态保存示例,如果header存在一些交互性行为,在onBindViewHolder里面需要绑定悬浮header的状态 11 | */ 12 | public int color = 0xff777777; 13 | 14 | public HeaderItem(String title) { 15 | this.title = title; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/stickyheaders/demo/model/Item.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.demo.model; 2 | 3 | public class Item { 4 | 5 | public final String title; 6 | public final String message; 7 | 8 | public Item(String title, String message) { 9 | this.title = title; 10 | this.message = message; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/layout/header_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 15 | 16 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item_view.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 | 22 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | StickyHeaders 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /art/screenshot.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/StickyHeaderRecyclerView/dcde3e96b5cb63d100d7fbe760cedfad8d8188b5/art/screenshot.gif -------------------------------------------------------------------------------- /art/screenshot.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/StickyHeaderRecyclerView/dcde3e96b5cb63d100d7fbe760cedfad8d8188b5/art/screenshot.mp4 -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | maven { url "https://jitpack.io" } 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:3.4.2' 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 10 | } 11 | } 12 | 13 | allprojects { 14 | repositories { 15 | google() 16 | mavenCentral() 17 | maven { url "https://jitpack.io" } 18 | } 19 | 20 | tasks.withType(Javadoc) { 21 | options.addStringOption('Xdoclint:none', '-quiet') 22 | options.addStringOption('encoding', 'UTF-8') 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.useAndroidX=false 2 | android.enableJetifier=false 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/StickyHeaderRecyclerView/dcde3e96b5cb63d100d7fbe760cedfad8d8188b5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Aug 05 17:34:35 CST 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.5.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':stickyheaders' 2 | -------------------------------------------------------------------------------- /stickyheaders/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /local.properties 3 | -------------------------------------------------------------------------------- /stickyheaders/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | 4 | group = 'com.yuyang.library' 5 | 6 | android { 7 | compileSdkVersion 28 8 | 9 | defaultConfig { 10 | minSdkVersion 15 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | } 16 | 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | 24 | lintOptions { 25 | abortOnError false 26 | } 27 | 28 | } 29 | 30 | dependencies { 31 | api 'com.android.support:appcompat-v7:28.0.0' 32 | api("com.android.support:recyclerview-v7:28.0.0") 33 | } 34 | 35 | task androidJavadocs(type: Javadoc) { 36 | source = android.sourceSets.main.java.srcDirs 37 | } 38 | 39 | task androidJavadocsJar(type: Jar) { 40 | classifier = 'javadoc' 41 | from androidJavadocs.destinationDir 42 | } 43 | task androidSourcesJar(type: Jar) { 44 | classifier = 'sources' 45 | from android.sourceSets.main.java.srcDirs 46 | } 47 | -------------------------------------------------------------------------------- /stickyheaders/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/bgogetap/Desktop/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /stickyheaders/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /stickyheaders/src/main/java/com/yuyang/stickyheaders/AdapterDataProvider.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders; 2 | 3 | import java.util.List; 4 | 5 | public interface AdapterDataProvider { 6 | 7 | List getAdapterData(); 8 | } 9 | -------------------------------------------------------------------------------- /stickyheaders/src/main/java/com/yuyang/stickyheaders/StickyHeaderModel.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders; 2 | 3 | public interface StickyHeaderModel { 4 | } 5 | -------------------------------------------------------------------------------- /stickyheaders/src/main/java/com/yuyang/stickyheaders/StickyLinearLayoutManager.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders; 2 | 3 | import android.content.Context; 4 | 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.view.View; 9 | 10 | import com.yuyang.stickyheaders.handler.ViewHolderFactory; 11 | import com.yuyang.stickyheaders.handler.StickyHeaderHandler; 12 | 13 | import java.util.ArrayList; 14 | import java.util.LinkedHashMap; 15 | import java.util.List; 16 | import java.util.Map; 17 | 18 | public class StickyLinearLayoutManager extends LinearLayoutManager { 19 | 20 | private AdapterDataProvider mHeaderProvider; 21 | private StickyHeaderHandler mHeaderHandler; 22 | 23 | private List mHeaderPositions = new ArrayList<>(); 24 | 25 | private ViewHolderFactory viewHolderFactory; 26 | 27 | private int headerElevation = StickyHeaderHandler.NO_ELEVATION; 28 | 29 | @Nullable 30 | private StickyHeaderListener mHeaderListener; 31 | 32 | public StickyLinearLayoutManager(Context context, AdapterDataProvider headerProvider) { 33 | this(context, VERTICAL, false, headerProvider); 34 | } 35 | 36 | public StickyLinearLayoutManager(Context context, int orientation, boolean reverseLayout, AdapterDataProvider headerProvider) { 37 | super(context, orientation, reverseLayout); 38 | 39 | this.mHeaderProvider = headerProvider; 40 | } 41 | 42 | public void setStickyHeaderListener(@Nullable StickyHeaderListener listener) { 43 | this.mHeaderListener = listener; 44 | if (mHeaderHandler != null) { 45 | mHeaderHandler.setListener(listener); 46 | } 47 | } 48 | 49 | public void elevateHeaders(boolean elevateHeaders) { 50 | elevateHeaders(elevateHeaders ? StickyHeaderHandler.DEFAULT_ELEVATION : StickyHeaderHandler.NO_ELEVATION); 51 | } 52 | 53 | public void elevateHeaders(int dpElevation) { 54 | this.headerElevation = dpElevation > 0 ? dpElevation : StickyHeaderHandler.NO_ELEVATION; 55 | if (mHeaderHandler != null) { 56 | mHeaderHandler.setElevateHeaders(headerElevation); 57 | } 58 | } 59 | 60 | @Override 61 | public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) { 62 | super.onLayoutChildren(recycler, state); 63 | cacheHeaderPositions(); 64 | if (mHeaderHandler != null) { 65 | resetHeaderHandler(); 66 | } 67 | } 68 | 69 | @Override 70 | public void scrollToPosition(int position) { 71 | super.scrollToPositionWithOffset(position, 0); 72 | } 73 | 74 | @Override 75 | public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) { 76 | int scroll = super.scrollVerticallyBy(dy, recycler, state); 77 | if (Math.abs(scroll) > 0) { 78 | if (mHeaderHandler != null) { 79 | mHeaderHandler.updateHeaderState(findFirstVisibleItemPosition(), getVisibleHeaders(), viewHolderFactory, findFirstCompletelyVisibleItemPosition() == 0); 80 | } 81 | } 82 | return scroll; 83 | } 84 | 85 | @Override 86 | public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) { 87 | int scroll = super.scrollHorizontallyBy(dx, recycler, state); 88 | if (Math.abs(scroll) > 0) { 89 | if (mHeaderHandler != null) { 90 | mHeaderHandler.updateHeaderState(findFirstVisibleItemPosition(), getVisibleHeaders(), viewHolderFactory, findFirstCompletelyVisibleItemPosition() == 0); 91 | } 92 | } 93 | return scroll; 94 | } 95 | 96 | @Override 97 | public void removeAndRecycleAllViews(RecyclerView.Recycler recycler) { 98 | super.removeAndRecycleAllViews(recycler); 99 | if (mHeaderHandler != null) { 100 | mHeaderHandler.clearHeader(); 101 | } 102 | } 103 | 104 | @Override 105 | public void onAttachedToWindow(RecyclerView view) { 106 | viewHolderFactory = new ViewHolderFactory(view); 107 | mHeaderHandler = new StickyHeaderHandler(view); 108 | mHeaderHandler.setElevateHeaders(headerElevation); 109 | mHeaderHandler.setListener(mHeaderListener); 110 | if (mHeaderPositions.size() > 0) { 111 | mHeaderHandler.setHeaderPositions(mHeaderPositions); 112 | resetHeaderHandler(); 113 | } 114 | super.onAttachedToWindow(view); 115 | } 116 | 117 | @Override 118 | public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) { 119 | if (mHeaderHandler != null) { 120 | mHeaderHandler.clearVisibilityObserver(); 121 | } 122 | super.onDetachedFromWindow(view, recycler); 123 | } 124 | 125 | private void resetHeaderHandler() { 126 | mHeaderHandler.reset(getOrientation()); 127 | mHeaderHandler.updateHeaderState(findFirstVisibleItemPosition(), getVisibleHeaders(), viewHolderFactory, findFirstCompletelyVisibleItemPosition() == 0); 128 | } 129 | 130 | private Map getVisibleHeaders() { 131 | Map visibleHeaders = new LinkedHashMap<>(); 132 | 133 | for (int i = 0; i < getChildCount(); i++) { 134 | View view = getChildAt(i); 135 | int dataPosition = getPosition(view); 136 | if (mHeaderPositions.contains(dataPosition)) { 137 | visibleHeaders.put(dataPosition, view); 138 | } 139 | } 140 | return visibleHeaders; 141 | } 142 | 143 | private void cacheHeaderPositions() { 144 | mHeaderPositions.clear(); 145 | List adapterData = mHeaderProvider.getAdapterData(); 146 | if (adapterData == null) { 147 | if (mHeaderHandler != null) { 148 | mHeaderHandler.setHeaderPositions(mHeaderPositions); 149 | } 150 | return; 151 | } 152 | 153 | for (int i = 0; i < adapterData.size(); i++) { 154 | if (adapterData.get(i) instanceof StickyHeaderModel) { 155 | mHeaderPositions.add(i); 156 | } 157 | } 158 | if (mHeaderHandler != null) { 159 | mHeaderHandler.setHeaderPositions(mHeaderPositions); 160 | } 161 | } 162 | 163 | public interface StickyHeaderListener { 164 | 165 | void headerAttached(View headerView, int adapterPosition); 166 | 167 | void headerDetached(View headerView, int adapterPosition); 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /stickyheaders/src/main/java/com/yuyang/stickyheaders/handler/StickyHeaderHandler.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.handler; 2 | 3 | import android.content.Context; 4 | import android.os.Build; 5 | 6 | import android.support.annotation.Nullable; 7 | import android.support.annotation.Px; 8 | import android.support.v7.widget.LinearLayoutManager; 9 | import android.support.v7.widget.RecyclerView; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.view.ViewGroup.MarginLayoutParams; 13 | import android.view.ViewTreeObserver; 14 | 15 | import com.yuyang.stickyheaders.StickyLinearLayoutManager; 16 | 17 | import java.util.List; 18 | import java.util.Map; 19 | 20 | public final class StickyHeaderHandler { 21 | 22 | private static final int INVALID_POSITION = -1; 23 | 24 | public static final int NO_ELEVATION = -1; 25 | public static final int DEFAULT_ELEVATION = 5; 26 | 27 | private final RecyclerView mRecyclerView; 28 | private RecyclerView.ViewHolder currentViewHolder; 29 | private View currentHeader; 30 | 31 | private final boolean checkMargins; 32 | 33 | private List mHeaderPositions; 34 | 35 | private int orientation; 36 | private boolean dirty; 37 | 38 | private int lastBoundPosition = INVALID_POSITION; 39 | private float headerElevation = NO_ELEVATION; 40 | private int cachedElevation = NO_ELEVATION; 41 | 42 | @Nullable 43 | private StickyLinearLayoutManager.StickyHeaderListener listener; 44 | 45 | private final ViewTreeObserver.OnGlobalLayoutListener visibilityObserver = new ViewTreeObserver.OnGlobalLayoutListener() { 46 | @Override 47 | public void onGlobalLayout() { 48 | int visibility = StickyHeaderHandler.this.mRecyclerView.getVisibility(); 49 | if (currentHeader != null) { 50 | currentHeader.setVisibility(visibility); 51 | } 52 | } 53 | }; 54 | 55 | public StickyHeaderHandler(RecyclerView recyclerView) { 56 | this.mRecyclerView = recyclerView; 57 | checkMargins = recyclerViewHasPadding(); 58 | } 59 | 60 | public void setHeaderPositions(List headerPositions) { 61 | this.mHeaderPositions = headerPositions; 62 | } 63 | 64 | /** 65 | * @param firstVisiblePosition 第一个可见item 66 | * @param visibleHeaders 当前可见的所有header位置 67 | * @param viewFactory header视图构造器 68 | * @param atTop 第0个item完全可见 69 | */ 70 | public void updateHeaderState(int firstVisiblePosition, Map visibleHeaders, ViewHolderFactory viewFactory, boolean atTop) { 71 | int headerPositionToShow = atTop ? INVALID_POSITION : getHeaderPositionToShow(firstVisiblePosition, visibleHeaders.get(firstVisiblePosition)); 72 | View headerToCopy = visibleHeaders.get(headerPositionToShow); 73 | if (headerPositionToShow != lastBoundPosition) { 74 | if (headerPositionToShow == INVALID_POSITION || (checkMargins && headerAwayFromEdge(headerToCopy))) { 75 | // 如果header刚好贴边,就无需加入 76 | dirty = true; 77 | safeDetachHeader(); 78 | lastBoundPosition = INVALID_POSITION; 79 | } else { 80 | // 否则就创建一个header视图 81 | lastBoundPosition = headerPositionToShow; 82 | RecyclerView.ViewHolder viewHolder = viewFactory.getViewHolderForPosition(headerPositionToShow); 83 | attachHeader(viewHolder, headerPositionToShow); 84 | } 85 | } else if (checkMargins && headerAwayFromEdge(headerToCopy)) { 86 | detachHeader(lastBoundPosition); 87 | lastBoundPosition = INVALID_POSITION; 88 | } 89 | checkHeaderPositions(visibleHeaders); 90 | mRecyclerView.post(new Runnable() { 91 | @Override 92 | public void run() { 93 | checkElevation(); 94 | } 95 | }); 96 | } 97 | 98 | private void checkHeaderPositions(final Map visibleHeaders) { 99 | if (currentHeader == null) return; 100 | if (currentHeader.getHeight() == 0) { 101 | waitForLayoutAndRetry(visibleHeaders); 102 | return; 103 | } 104 | boolean reset = true; 105 | for (Map.Entry entry : visibleHeaders.entrySet()) { 106 | if (entry.getKey() <= lastBoundPosition) { 107 | continue; 108 | } 109 | View nextHeader = entry.getValue(); 110 | reset = offsetHeader(nextHeader) == -1; 111 | break; 112 | } 113 | if (reset) { 114 | resetTranslation(); 115 | } 116 | currentHeader.setVisibility(View.VISIBLE); 117 | } 118 | 119 | public void setElevateHeaders(int dpElevation) { 120 | if (dpElevation != NO_ELEVATION) { 121 | cachedElevation = dpElevation; 122 | } else { 123 | headerElevation = NO_ELEVATION; 124 | cachedElevation = NO_ELEVATION; 125 | } 126 | } 127 | 128 | public void reset(int orientation) { 129 | this.orientation = orientation; 130 | lastBoundPosition = INVALID_POSITION; 131 | dirty = true; 132 | safeDetachHeader(); 133 | } 134 | 135 | public void clearHeader() { 136 | detachHeader(lastBoundPosition); 137 | } 138 | 139 | public void clearVisibilityObserver() { 140 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 141 | mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(visibilityObserver); 142 | } else { 143 | mRecyclerView.getViewTreeObserver().removeGlobalOnLayoutListener(visibilityObserver); 144 | } 145 | } 146 | 147 | public void setListener(@Nullable StickyLinearLayoutManager.StickyHeaderListener listener) { 148 | this.listener = listener; 149 | } 150 | 151 | private float offsetHeader(View nextHeader) { 152 | boolean shouldOffsetHeader = shouldOffsetHeader(nextHeader); 153 | float offset = -1; 154 | if (shouldOffsetHeader) { 155 | if (orientation == LinearLayoutManager.VERTICAL) { 156 | offset = -(currentHeader.getHeight() - nextHeader.getY()); 157 | currentHeader.setTranslationY(offset); 158 | } else { 159 | offset = -(currentHeader.getWidth() - nextHeader.getX()); 160 | currentHeader.setTranslationX(offset); 161 | } 162 | } 163 | return offset; 164 | } 165 | 166 | private boolean shouldOffsetHeader(View nextHeader) { 167 | if (orientation == LinearLayoutManager.VERTICAL) { 168 | return nextHeader.getY() < currentHeader.getHeight(); 169 | } else { 170 | return nextHeader.getX() < currentHeader.getWidth(); 171 | } 172 | } 173 | 174 | private void resetTranslation() { 175 | if (orientation == LinearLayoutManager.VERTICAL) { 176 | currentHeader.setTranslationY(0); 177 | } else { 178 | currentHeader.setTranslationX(0); 179 | } 180 | } 181 | 182 | private int getHeaderPositionToShow(int firstVisiblePosition, @Nullable View headerForPosition) { 183 | int headerPositionToShow = INVALID_POSITION; 184 | if (headerIsOffset(headerForPosition)) { 185 | int offsetHeaderIndex = mHeaderPositions.indexOf(firstVisiblePosition); 186 | if (offsetHeaderIndex > 0) { 187 | return mHeaderPositions.get(offsetHeaderIndex - 1); 188 | } 189 | } 190 | for (Integer headerPosition : mHeaderPositions) { 191 | if (headerPosition <= firstVisiblePosition) { 192 | // 寻找第一个可见的 item 所关联的 header 的位置 193 | headerPositionToShow = headerPosition; 194 | } else { 195 | break; 196 | } 197 | } 198 | return headerPositionToShow; 199 | } 200 | 201 | private boolean headerIsOffset(View headerForPosition) { 202 | return headerForPosition != null && (orientation == LinearLayoutManager.VERTICAL ? headerForPosition.getY() > 0 : headerForPosition.getX() > 0); 203 | } 204 | 205 | private void attachHeader(RecyclerView.ViewHolder viewHolder, int headerPosition) { 206 | if (currentViewHolder == viewHolder) { 207 | callDetach(lastBoundPosition); 208 | mRecyclerView.getAdapter().onBindViewHolder(currentViewHolder, headerPosition); 209 | currentViewHolder.itemView.requestLayout(); 210 | checkTranslation(); 211 | callAttach(headerPosition); 212 | dirty = false; 213 | return; 214 | } 215 | detachHeader(lastBoundPosition); 216 | this.currentViewHolder = viewHolder; 217 | mRecyclerView.getAdapter().onBindViewHolder(currentViewHolder, headerPosition); 218 | this.currentHeader = currentViewHolder.itemView; 219 | callAttach(headerPosition); 220 | resolveElevationSettings(currentHeader.getContext()); 221 | currentHeader.setVisibility(View.INVISIBLE); 222 | mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(visibilityObserver); 223 | getRecyclerParent().addView(currentHeader); 224 | if (checkMargins) { 225 | updateLayoutParams(currentHeader); 226 | } 227 | dirty = false; 228 | } 229 | 230 | private int currentDimension() { 231 | if (currentHeader == null) { 232 | return 0; 233 | } 234 | if (orientation == LinearLayoutManager.VERTICAL) { 235 | return currentHeader.getHeight(); 236 | } else { 237 | return currentHeader.getWidth(); 238 | } 239 | } 240 | 241 | private boolean headerHasTranslation() { 242 | if (currentHeader == null) { 243 | return false; 244 | } 245 | if (orientation == LinearLayoutManager.VERTICAL) { 246 | return currentHeader.getTranslationY() < 0; 247 | } else { 248 | return currentHeader.getTranslationX() < 0; 249 | } 250 | } 251 | 252 | private void updateTranslation(int diff) { 253 | if (currentHeader == null) { 254 | return; 255 | } 256 | if (orientation == LinearLayoutManager.VERTICAL) { 257 | currentHeader.setTranslationY(currentHeader.getTranslationY() + diff); 258 | } else { 259 | currentHeader.setTranslationX(currentHeader.getTranslationX() + diff); 260 | } 261 | } 262 | 263 | private void checkTranslation() { 264 | final View view = currentHeader; 265 | if (view == null) return; 266 | view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 267 | int previous = currentDimension(); 268 | 269 | @Override 270 | public void onGlobalLayout() { 271 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 272 | view.getViewTreeObserver().removeOnGlobalLayoutListener(this); 273 | } else { 274 | view.getViewTreeObserver().removeGlobalOnLayoutListener(this); 275 | } 276 | if (currentHeader == null) return; 277 | 278 | int newDimen = currentDimension(); 279 | if (headerHasTranslation() && previous != newDimen) { 280 | updateTranslation(previous - newDimen); 281 | } 282 | } 283 | }); 284 | } 285 | 286 | private void checkElevation() { 287 | if (headerElevation != NO_ELEVATION && currentHeader != null) { 288 | if (orientation == LinearLayoutManager.VERTICAL && currentHeader.getTranslationY() == 0 289 | || orientation == LinearLayoutManager.HORIZONTAL && currentHeader.getTranslationX() == 0) { 290 | elevateHeader(); 291 | } else { 292 | settleHeader(); 293 | } 294 | } 295 | } 296 | 297 | private void elevateHeader() { 298 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 299 | if (currentHeader.getTag() != null) { 300 | return; 301 | } 302 | currentHeader.setTag(true); 303 | currentHeader.animate().z(headerElevation); 304 | } 305 | } 306 | 307 | private void settleHeader() { 308 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 309 | if (currentHeader.getTag() != null) { 310 | currentHeader.setTag(null); 311 | currentHeader.animate().z(0); 312 | } 313 | } 314 | } 315 | 316 | private void detachHeader(int position) { 317 | if (currentHeader != null) { 318 | getRecyclerParent().removeView(currentHeader); 319 | callDetach(position); 320 | clearVisibilityObserver(); 321 | currentHeader = null; 322 | currentViewHolder = null; 323 | } 324 | } 325 | 326 | private void callAttach(int position) { 327 | if (listener != null) { 328 | listener.headerAttached(currentHeader, position); 329 | } 330 | } 331 | 332 | private void callDetach(int position) { 333 | if (listener != null) { 334 | listener.headerDetached(currentHeader, position); 335 | } 336 | } 337 | 338 | private void updateLayoutParams(View currentHeader) { 339 | MarginLayoutParams params = (MarginLayoutParams) currentHeader.getLayoutParams(); 340 | matchMarginsToPadding(params); 341 | } 342 | 343 | private void matchMarginsToPadding(MarginLayoutParams layoutParams) { 344 | @Px int leftMargin = orientation == LinearLayoutManager.VERTICAL ? mRecyclerView.getPaddingLeft() : 0; 345 | @Px int topMargin = orientation == LinearLayoutManager.VERTICAL ? 0 : mRecyclerView.getPaddingTop(); 346 | @Px int rightMargin = orientation == LinearLayoutManager.VERTICAL ? mRecyclerView.getPaddingRight() : 0; 347 | layoutParams.setMargins(leftMargin, topMargin, rightMargin, 0); 348 | } 349 | 350 | private boolean headerAwayFromEdge(View headerToCopy) { 351 | return headerToCopy != null && (orientation == LinearLayoutManager.VERTICAL ? headerToCopy.getY() > 0 : headerToCopy.getX() > 0); 352 | } 353 | 354 | private boolean recyclerViewHasPadding() { 355 | return mRecyclerView.getPaddingLeft() > 0 || mRecyclerView.getPaddingRight() > 0 || mRecyclerView.getPaddingTop() > 0; 356 | } 357 | 358 | private ViewGroup getRecyclerParent() { 359 | return (ViewGroup) mRecyclerView.getParent(); 360 | } 361 | 362 | private void waitForLayoutAndRetry(final Map visibleHeaders) { 363 | final View view = currentHeader; 364 | if (view == null) return; 365 | view.getViewTreeObserver().addOnGlobalLayoutListener( 366 | new ViewTreeObserver.OnGlobalLayoutListener() { 367 | @Override 368 | public void onGlobalLayout() { 369 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 370 | view.getViewTreeObserver().removeOnGlobalLayoutListener(this); 371 | } else { 372 | view.getViewTreeObserver().removeGlobalOnLayoutListener(this); 373 | } 374 | if (currentHeader == null) return; 375 | getRecyclerParent().requestLayout(); 376 | checkHeaderPositions(visibleHeaders); 377 | } 378 | }); 379 | } 380 | 381 | private void safeDetachHeader() { 382 | final int cachedPosition = lastBoundPosition; 383 | getRecyclerParent().post(new Runnable() { 384 | @Override 385 | public void run() { 386 | if (dirty) { 387 | detachHeader(cachedPosition); 388 | } 389 | } 390 | }); 391 | } 392 | 393 | private void resolveElevationSettings(Context context) { 394 | if (cachedElevation != NO_ELEVATION && headerElevation == NO_ELEVATION) { 395 | headerElevation = dp2px(context, cachedElevation); 396 | } 397 | } 398 | 399 | private float dp2px(Context context, int dp) { 400 | float scale = context.getResources().getDisplayMetrics().density; 401 | return dp * scale; 402 | } 403 | } 404 | -------------------------------------------------------------------------------- /stickyheaders/src/main/java/com/yuyang/stickyheaders/handler/ViewHolderFactory.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.stickyheaders.handler; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | import android.view.ViewGroup; 5 | 6 | public final class ViewHolderFactory { 7 | 8 | private final RecyclerView recyclerView; 9 | 10 | private RecyclerView.ViewHolder currentViewHolder; 11 | 12 | private int currentViewType; 13 | 14 | public ViewHolderFactory(RecyclerView recyclerView) { 15 | this.recyclerView = recyclerView; 16 | this.currentViewType = -1; 17 | } 18 | 19 | public RecyclerView.ViewHolder getViewHolderForPosition(int position) { 20 | if (currentViewType != recyclerView.getAdapter().getItemViewType(position)) { 21 | currentViewType = recyclerView.getAdapter().getItemViewType(position); 22 | currentViewHolder = recyclerView.getAdapter().createViewHolder((ViewGroup) recyclerView.getParent(), currentViewType); 23 | } 24 | return currentViewHolder; 25 | } 26 | } --------------------------------------------------------------------------------