├── .gitignore ├── LICENSE ├── NestedWebViewRecyclerViewGroup ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── hzw │ │ └── nested │ │ ├── NestedScrollWebView.java │ │ ├── NestedWebViewRecyclerViewGroup.java │ │ ├── ScrollBarView.java │ │ ├── Util.java │ │ └── onScrollListener.java │ └── res │ └── values │ └── attr.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── example │ └── example.gif ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── hzw │ │ └── nested │ │ └── example │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── hzw │ │ │ └── nested │ │ │ └── example │ │ │ ├── CommentFragment.java │ │ │ ├── CustomerWebView.java │ │ │ ├── Entity.java │ │ │ ├── MainActivity.java │ │ │ ├── NestedActivity.java │ │ │ ├── NestedFragmentActivity.java │ │ │ ├── ReadUtil.java │ │ │ ├── RvAdapter.java │ │ │ └── WrapRvActivity.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_nested.xml │ │ ├── activity_nested_fragment.xml │ │ ├── activity_wrap_rv.xml │ │ ├── fragment_comment.xml │ │ ├── item_about.xml │ │ ├── item_comment.xml │ │ ├── item_divider.xml │ │ └── item_image.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ ├── ic_launcher_round.png │ │ ├── icon.jpeg │ │ ├── image.png │ │ └── user.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── hzw │ └── nested │ └── example │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | -------------------------------------------------------------------------------- /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 [2019] [hzwSunshine] 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 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: "guru.stefma.bintrayrelease" 3 | 4 | android { 5 | compileSdkVersion 28 6 | 7 | defaultConfig { 8 | minSdkVersion 17 9 | targetSdkVersion 28 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | 22 | version = "1.2.2" 23 | group = "com.github.hzw" 24 | androidArtifact { 25 | artifactId = "NestedWebViewRecyclerViewGroup" 26 | } 27 | publish { 28 | userOrg = 'hzwsunshine' 29 | desc = 'This is a ViewGroup of WebView and RecyclerView' 30 | website = 'https://github.com/HzwSunshine/NestedWebViewRecyclerViewGroup' 31 | } 32 | 33 | } 34 | 35 | dependencies { 36 | compileOnly 'com.android.support:support-v4:28.0.0' 37 | compileOnly 'com.android.support:recyclerview-v7:28.0.0' 38 | } 39 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/java/com/hzw/nested/NestedScrollWebView.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.view.NestedScrollingChild2; 6 | import android.support.v4.view.NestedScrollingChildHelper; 7 | import android.support.v4.view.ViewCompat; 8 | import android.util.AttributeSet; 9 | import android.view.MotionEvent; 10 | import android.view.VelocityTracker; 11 | import android.view.View; 12 | import android.view.ViewConfiguration; 13 | import android.webkit.WebView; 14 | import android.widget.Scroller; 15 | 16 | /** 17 | * author: hzw 18 | * time: 2019/2/25 下午2:08 19 | * description: {@link NestedWebViewRecyclerViewGroup}的子View,用于协作和RecyclerView的联合滑动 20 | */ 21 | public class NestedScrollWebView extends WebView implements NestedScrollingChild2 { 22 | 23 | private final int[] mScrollConsumed = new int[2]; 24 | private NestedWebViewRecyclerViewGroup parent; 25 | private NestedScrollingChildHelper childHelper; 26 | private VelocityTracker velocityTracker; 27 | private Scroller scroller; 28 | private boolean isSelfFling; 29 | private boolean hasFling; 30 | private final float density; 31 | private int mWebViewContentHeight; 32 | private int mMaximumVelocity; 33 | private int maxScrollY; 34 | private int TouchSlop; 35 | private int firstY; 36 | private int lastY; 37 | 38 | public NestedScrollWebView(Context context) { 39 | this(context, null); 40 | } 41 | 42 | public NestedScrollWebView(Context context, AttributeSet attrs) { 43 | this(context, attrs, 0); 44 | } 45 | 46 | public NestedScrollWebView(Context context, AttributeSet attrs, int defStyleAttr) { 47 | super(context, attrs, defStyleAttr); 48 | childHelper = new NestedScrollingChildHelper(this); 49 | setNestedScrollingEnabled(true); 50 | scroller = new Scroller(getContext()); 51 | ViewConfiguration configuration = ViewConfiguration.get(getContext()); 52 | mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); 53 | density = getResources().getDisplayMetrics().density; 54 | //TouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); 55 | TouchSlop = Util.dip2px(3); 56 | } 57 | 58 | @Override 59 | public boolean onTouchEvent(MotionEvent event) { 60 | switch (event.getAction()) { 61 | case MotionEvent.ACTION_DOWN: 62 | mWebViewContentHeight = 0; 63 | lastY = (int) event.getRawY(); 64 | firstY = lastY; 65 | if (!scroller.isFinished()) { 66 | scroller.abortAnimation(); 67 | } 68 | initOrResetVelocityTracker(); 69 | isSelfFling = false; 70 | hasFling = false; 71 | maxScrollY = getWebViewContentHeight() - getHeight(); 72 | startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); 73 | break; 74 | case MotionEvent.ACTION_MOVE: 75 | initVelocityTrackerIfNotExists(); 76 | velocityTracker.addMovement(event); 77 | int y = (int) (event.getRawY()); 78 | int dy = y - lastY; 79 | lastY = y; 80 | if (!dispatchNestedPreScroll(0, -dy, mScrollConsumed, null)) { 81 | scrollBy(0, -dy); 82 | } 83 | if (Math.abs(firstY - y) > TouchSlop) { 84 | //屏蔽WebView本身的滑动,滑动事件自己处理 85 | event.setAction(MotionEvent.ACTION_CANCEL); 86 | } 87 | break; 88 | case MotionEvent.ACTION_CANCEL: 89 | case MotionEvent.ACTION_UP: 90 | if (isParentResetScroll() && velocityTracker != null) { 91 | velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); 92 | int yVelocity = (int) -velocityTracker.getYVelocity(); 93 | recycleVelocityTracker(); 94 | isSelfFling = true; 95 | flingScroll(0, yVelocity); 96 | } 97 | break; 98 | } 99 | super.onTouchEvent(event); 100 | return true; 101 | } 102 | 103 | @Override 104 | public void flingScroll(int vx, int vy) { 105 | int startY = getWebViewContentHeight() - getHeight(); 106 | if (getScrollY() < startY) { 107 | startY = getScrollY(); 108 | } 109 | scroller.fling(0, startY, 0, vy, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE); 110 | scroller.computeScrollOffset(); 111 | invalidate(); 112 | } 113 | 114 | @Override 115 | protected void onDetachedFromWindow() { 116 | super.onDetachedFromWindow(); 117 | recycleVelocityTracker(); 118 | stopScroll(); 119 | childHelper = null; 120 | scroller = null; 121 | parent = null; 122 | } 123 | 124 | @Override 125 | public void computeScroll() { 126 | if (scroller.computeScrollOffset()) { 127 | final int currY = scroller.getCurrY(); 128 | if (!isSelfFling) {//parent fling 129 | scrollTo(0, currY); 130 | invalidate(); 131 | return; 132 | } 133 | if (isWebViewCanScroll()) { 134 | scrollTo(0, currY); 135 | invalidate(); 136 | } 137 | if (!hasFling && scroller.getStartY() < currY 138 | && !canWebViewScrollDown() 139 | && startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL) 140 | && !dispatchNestedPreFling(0, scroller.getCurrVelocity())) { 141 | //滑动到底部时,将fling传递给父控件和RecyclerView 142 | hasFling = true; 143 | dispatchNestedFling(0, scroller.getCurrVelocity(), false); 144 | } 145 | } 146 | } 147 | 148 | @Override 149 | public void scrollTo(int x, int y) { 150 | if (isParentResetScroll()) { 151 | if (maxScrollY != 0 && y > maxScrollY) { 152 | y = maxScrollY; 153 | } 154 | if (y < 0) { 155 | y = 0; 156 | } 157 | super.scrollTo(x, y); 158 | 159 | //用于父控件不是嵌套控件时,绘制进度条,仅此而已 160 | if (!(getParent() instanceof NestedWebViewRecyclerViewGroup)) { 161 | startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL); 162 | dispatchNestedScroll(1, 0, 0, 0, null); 163 | } 164 | } 165 | } 166 | 167 | void stopScroll() { 168 | if (scroller != null && !scroller.isFinished()) { 169 | scroller.abortAnimation(); 170 | } 171 | } 172 | 173 | void scrollToBottom() { 174 | int y = computeVerticalScrollRange(); 175 | super.scrollTo(0, y - getHeight()); 176 | } 177 | 178 | private void initWebViewParent() { 179 | if (this.parent != null) { 180 | return; 181 | } 182 | View parent = (View) getParent(); 183 | while (parent != null) { 184 | if (parent instanceof NestedWebViewRecyclerViewGroup) { 185 | this.parent = (NestedWebViewRecyclerViewGroup) parent; 186 | break; 187 | } else { 188 | parent = (View) parent.getParent(); 189 | } 190 | } 191 | } 192 | 193 | private boolean isParentResetScroll() { 194 | if (parent == null) { 195 | initWebViewParent(); 196 | } 197 | if (parent != null) { 198 | return parent.getScrollY() == 0; 199 | } 200 | return true; 201 | } 202 | 203 | private void initOrResetVelocityTracker() { 204 | if (velocityTracker == null) { 205 | velocityTracker = VelocityTracker.obtain(); 206 | } else { 207 | velocityTracker.clear(); 208 | } 209 | } 210 | 211 | private void initVelocityTrackerIfNotExists() { 212 | if (velocityTracker == null) { 213 | velocityTracker = VelocityTracker.obtain(); 214 | } 215 | } 216 | 217 | private void recycleVelocityTracker() { 218 | if (velocityTracker != null) { 219 | velocityTracker.recycle(); 220 | velocityTracker = null; 221 | } 222 | } 223 | 224 | private boolean canWebViewScrollDown() { 225 | final int offset = getScrollY(); 226 | final int range = getWebViewContentHeight() - getHeight(); 227 | if (range == 0) { 228 | return false; 229 | } 230 | return offset < range - 3; 231 | } 232 | 233 | private boolean isWebViewCanScroll() { 234 | final int offset = getScrollY(); 235 | final int range = getWebViewContentHeight() - getHeight(); 236 | if (range == 0) { 237 | return false; 238 | } 239 | return offset > 0 || offset < range - 3; 240 | } 241 | 242 | private int getWebViewContentHeight() { 243 | if (mWebViewContentHeight == 0) { 244 | mWebViewContentHeight = (int) (getContentHeight() * density); 245 | } 246 | return mWebViewContentHeight; 247 | } 248 | 249 | private NestedScrollingChildHelper getHelper() { 250 | if (childHelper == null) { 251 | childHelper = new NestedScrollingChildHelper(this); 252 | } 253 | return childHelper; 254 | } 255 | 256 | @Override 257 | public boolean startNestedScroll(int axes, int type) { 258 | return getHelper().startNestedScroll(axes, type); 259 | } 260 | 261 | @Override 262 | public void stopNestedScroll(int type) { 263 | getHelper().stopNestedScroll(type); 264 | } 265 | 266 | @Override 267 | public boolean hasNestedScrollingParent(int type) { 268 | return getHelper().hasNestedScrollingParent(type); 269 | } 270 | 271 | @Override 272 | public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, 273 | int dyUnconsumed, @Nullable int[] offsetInWindow, int type) { 274 | return getHelper().dispatchNestedScroll(dxConsumed, dyConsumed, 275 | dxUnconsumed, dyUnconsumed, offsetInWindow, type); 276 | } 277 | 278 | @Override 279 | public boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow, int type) { 280 | return getHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow, type); 281 | } 282 | 283 | @Override 284 | public void setNestedScrollingEnabled(boolean enabled) { 285 | getHelper().setNestedScrollingEnabled(enabled); 286 | } 287 | 288 | @Override 289 | public boolean isNestedScrollingEnabled() { 290 | return getHelper().isNestedScrollingEnabled(); 291 | } 292 | 293 | @Override 294 | public boolean startNestedScroll(int axes) { 295 | return getHelper().startNestedScroll(axes); 296 | } 297 | 298 | @Override 299 | public void stopNestedScroll() { 300 | getHelper().stopNestedScroll(); 301 | } 302 | 303 | @Override 304 | public boolean hasNestedScrollingParent() { 305 | return getHelper().hasNestedScrollingParent(); 306 | } 307 | 308 | @Override 309 | public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, 310 | @Nullable int[] offsetInWindow) { 311 | return getHelper().dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow); 312 | } 313 | 314 | @Override 315 | public boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed, @Nullable int[] offsetInWindow) { 316 | return getHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow); 317 | } 318 | 319 | @Override 320 | public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 321 | return getHelper().dispatchNestedFling(velocityX, velocityY, consumed); 322 | } 323 | 324 | @Override 325 | public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 326 | return getHelper().dispatchNestedPreFling(velocityX, velocityY); 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/java/com/hzw/nested/NestedWebViewRecyclerViewGroup.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.graphics.Canvas; 6 | import android.graphics.Color; 7 | import android.support.annotation.NonNull; 8 | import android.support.v4.view.NestedScrollingParent2; 9 | import android.support.v4.view.NestedScrollingParentHelper; 10 | import android.support.v4.view.ViewCompat; 11 | import android.support.v7.widget.LinearLayoutManager; 12 | import android.support.v7.widget.RecyclerView; 13 | import android.util.AttributeSet; 14 | import android.view.MotionEvent; 15 | import android.view.VelocityTracker; 16 | import android.view.View; 17 | import android.view.ViewConfiguration; 18 | import android.view.ViewGroup; 19 | import android.widget.Scroller; 20 | 21 | /** 22 | * author: hzw 23 | * time: 2019/2/25 下午2:08 24 | * description: {@link NestedScrollWebView}和RecyclerView的嵌套类 25 | */ 26 | public class NestedWebViewRecyclerViewGroup extends ViewGroup implements NestedScrollingParent2 { 27 | 28 | //WebView向RecyclerView滑动 29 | private static final int SCROLL_WEB_PARENT = 0; 30 | //父控件向WebView滑动,位于父控件的dispatchTouchEvent事件中 31 | private static final int SCROLL_PARENT_WEB = 1; 32 | //RecyclerView向父控件滑动,位于RecyclerView的fling事件中 33 | private static final int SCROLL_RV_PARENT = 2; 34 | //上下切换 35 | private static final int SCROLL_SWITCH = 3; 36 | 37 | private NestedScrollingParentHelper helper; 38 | private VelocityTracker velocityTracker; 39 | private NestedScrollWebView webView; 40 | private onScrollListener listener; 41 | private RecyclerView recyclerView; 42 | private ScrollBarView scrollbar; 43 | private Scroller scroller; 44 | private Runnable runnable; 45 | 46 | private final int switchDuration; 47 | private int webViewContentHeight; 48 | private int currentScrollType; 49 | private int rvContentHeight; 50 | private int maximumVelocity; 51 | private final float density; 52 | private int webViewHeight; 53 | private int totalHeight; 54 | private int maxScrollY; 55 | 56 | //是否在上下切换滑动中... 57 | private boolean isSwitching; 58 | private boolean hasFling; 59 | private boolean isRvFlingDown; 60 | private boolean isRvShow; 61 | 62 | 63 | public NestedWebViewRecyclerViewGroup(Context context) { 64 | this(context, null); 65 | } 66 | 67 | public NestedWebViewRecyclerViewGroup(Context context, AttributeSet attrs) { 68 | this(context, attrs, 0); 69 | } 70 | 71 | public NestedWebViewRecyclerViewGroup(Context context, AttributeSet attrs, int defStyleAttr) { 72 | super(context, attrs, defStyleAttr); 73 | setWillNotDraw(false); 74 | helper = new NestedScrollingParentHelper(this); 75 | scroller = new Scroller(getContext()); 76 | density = getResources().getDisplayMetrics().density; 77 | ViewConfiguration configuration = ViewConfiguration.get(getContext()); 78 | maximumVelocity = configuration.getScaledMaximumFlingVelocity(); 79 | TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.NestedWebViewRecyclerViewGroup, defStyleAttr, 0); 80 | switchDuration = array.getInteger(R.styleable.NestedWebViewRecyclerViewGroup_switchDuration, 300); 81 | boolean scrollbarEnable = array.getBoolean(R.styleable.NestedWebViewRecyclerViewGroup_scrollbarEnable, true); 82 | if (scrollbarEnable) { 83 | scrollbar = new ScrollBarView(getContext()); 84 | int color = array.getColor(R.styleable.NestedWebViewRecyclerViewGroup_scrollbarColor, Color.LTGRAY); 85 | float space = array.getDimension(R.styleable.NestedWebViewRecyclerViewGroup_scrollbarMarginRight, Util.dip2px(3)); 86 | float barWidth = array.getDimension(R.styleable.NestedWebViewRecyclerViewGroup_scrollbarWidth, Util.dip2px(4)); 87 | float barMinHeight = array.getDimension(R.styleable.NestedWebViewRecyclerViewGroup_scrollbarMinHeight, Util.dip2px(30)); 88 | scrollbar.init(color, (int) space, (int) barWidth, (int) barMinHeight); 89 | } 90 | array.recycle(); 91 | } 92 | 93 | @Override 94 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 95 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 96 | if (getChildCount() < 1 || getChildCount() > 3) { 97 | if (BuildConfig.DEBUG) { 98 | throw new IllegalStateException("Please check child layout, " + 99 | "child must be NestedScrollWebView and RecyclerView"); 100 | } 101 | return; 102 | } 103 | int widthMode = MeasureSpec.getMode(widthMeasureSpec); 104 | int measureWidth = MeasureSpec.getSize(widthMeasureSpec); 105 | int measureHeight = MeasureSpec.getSize(heightMeasureSpec); 106 | int width = measureWidth; 107 | if (widthMode != MeasureSpec.EXACTLY) { 108 | width = getContext().getResources().getDisplayMetrics().widthPixels; 109 | } 110 | int count = getChildCount(); 111 | totalHeight = 0; 112 | for (int i = 0; i < count; i++) { 113 | View child = getChildAt(i); 114 | measureChild(child, widthMeasureSpec, heightMeasureSpec); 115 | if (child.getVisibility() != GONE && !(child instanceof ScrollBarView)) { 116 | totalHeight += child.getMeasuredHeight(); 117 | } 118 | } 119 | setMeasuredDimension(width, measureHeight); 120 | } 121 | 122 | @Override 123 | protected void onLayout(boolean changed, int l, int t, int r, int b) { 124 | int childTotalHeight = 0; 125 | for (int i = 0; i < getChildCount(); i++) { 126 | View child = getChildAt(i); 127 | int childWidth = child.getMeasuredWidth(); 128 | int childHeight = child.getMeasuredHeight(); 129 | childHeight = child.getVisibility() != GONE ? childHeight : 0; 130 | if (child instanceof ScrollBarView) { 131 | bringChildToFront(child); 132 | child.layout(getMeasuredWidth() - childWidth, 0, childHeight, totalHeight); 133 | } else { 134 | child.layout(0, childTotalHeight, childWidth, childTotalHeight + childHeight); 135 | } 136 | childTotalHeight += childHeight; 137 | } 138 | fixScroll(); 139 | if (!isSwitching) { 140 | fixError(); 141 | } 142 | } 143 | 144 | private void fixScroll() { 145 | rvContentHeight = 0; 146 | webViewContentHeight = 0; 147 | if (webView != null) { 148 | webViewHeight = webView.getMeasuredHeight(); 149 | } 150 | if (getMaxScrollY() < getScrollY() && getScrollY() > 0) { 151 | scrollTo(0, maxScrollY); 152 | } 153 | } 154 | 155 | private int getMaxScrollY() { 156 | //maxScrollY==0说明RV高度为0 157 | //maxScrollY<0说明内容不足父控件高度 158 | maxScrollY = totalHeight - getMeasuredHeight(); 159 | maxScrollY = maxScrollY < 0 ? 0 : maxScrollY; 160 | return maxScrollY; 161 | } 162 | 163 | @Override 164 | protected void onFinishInflate() { 165 | super.onFinishInflate(); 166 | if (getChildCount() < 1) return; 167 | int count = getChildCount(); 168 | for (int i = 0; i < count; i++) { 169 | View child = getChildAt(i); 170 | if (child instanceof NestedScrollWebView) { 171 | webView = (NestedScrollWebView) child; 172 | } else if (child instanceof RecyclerView) { 173 | recyclerView = (RecyclerView) child; 174 | } 175 | } 176 | if (scrollbar != null && scrollbar.getParent() == null) { 177 | addView(scrollbar); 178 | } 179 | runnable = new Runnable() { 180 | @Override 181 | public void run() { 182 | if (webView != null) { 183 | webViewHeight = webView.getHeight(); 184 | } else { 185 | findWebView(NestedWebViewRecyclerViewGroup.this); 186 | } 187 | //找不到RecyclerView时,会在界面显示时再次尝试重新获取 188 | findRecyclerView(NestedWebViewRecyclerViewGroup.this); 189 | } 190 | }; 191 | post(runnable); 192 | } 193 | 194 | private void findRecyclerView(ViewGroup parent) { 195 | if (recyclerView != null) return; 196 | int count = parent.getChildCount(); 197 | for (int i = 0; i < count; i++) { 198 | View child = parent.getChildAt(i); 199 | if (child instanceof RecyclerView) { 200 | recyclerView = (RecyclerView) child; 201 | break; 202 | } 203 | if (child instanceof ViewGroup && recyclerView == null) { 204 | findRecyclerView((ViewGroup) child); 205 | } 206 | } 207 | } 208 | 209 | private void findWebView(ViewGroup parent) { 210 | if (webView != null) return; 211 | int count = parent.getChildCount(); 212 | for (int i = 0; i < count; i++) { 213 | View child = parent.getChildAt(i); 214 | if (child instanceof NestedScrollWebView) { 215 | webView = (NestedScrollWebView) child; 216 | break; 217 | } 218 | if (child instanceof ViewGroup && webView == null) { 219 | findWebView((ViewGroup) child); 220 | } 221 | } 222 | if (webView != null) { 223 | webViewHeight = webView.getHeight(); 224 | super.requestLayout(); 225 | } 226 | } 227 | 228 | /** 229 | * 特殊的布局中,如果无法获取到RecyclerView,请手动设置 230 | */ 231 | public void setRecyclerView(RecyclerView recyclerView) { 232 | if (this.recyclerView != null) { 233 | return; 234 | } 235 | this.recyclerView = recyclerView; 236 | } 237 | 238 | /** 239 | * 只用于处理父控件的fling事件,其他的事件不处理 240 | */ 241 | @Override 242 | public boolean dispatchTouchEvent(MotionEvent event) { 243 | if (isSwitching) { 244 | return true; 245 | } 246 | switch (event.getAction()) { 247 | case MotionEvent.ACTION_DOWN: 248 | webViewContentHeight = 0; 249 | rvContentHeight = 0; 250 | hasFling = false; 251 | isRvFlingDown = false; 252 | initOrResetVelocityTracker(); 253 | resetScroller(); 254 | getMaxScrollY(); 255 | fixError(); 256 | isRVShow(); 257 | break; 258 | case MotionEvent.ACTION_MOVE: 259 | initVelocityTrackerIfNotExists(); 260 | velocityTracker.addMovement(event); 261 | break; 262 | case MotionEvent.ACTION_CANCEL: 263 | case MotionEvent.ACTION_UP: 264 | if (isParentCenter() && velocityTracker != null) { 265 | //处理连接处的父控件fling事件 266 | velocityTracker.computeCurrentVelocity(1000, maximumVelocity); 267 | int yVelocity = (int) -velocityTracker.getYVelocity(); 268 | currentScrollType = yVelocity > 0 ? SCROLL_WEB_PARENT : SCROLL_PARENT_WEB; 269 | recycleVelocityTracker(); 270 | parentFling(yVelocity); 271 | } 272 | break; 273 | } 274 | return super.dispatchTouchEvent(event); 275 | } 276 | 277 | private void resetScroller() { 278 | if (!scroller.isFinished()) { 279 | scroller.abortAnimation(); 280 | } 281 | if (recyclerView != null) { 282 | recyclerView.stopScroll(); 283 | } 284 | if (webView != null) { 285 | webView.stopScroll(); 286 | } 287 | } 288 | 289 | private void initOrResetVelocityTracker() { 290 | if (velocityTracker == null) { 291 | velocityTracker = VelocityTracker.obtain(); 292 | } else { 293 | velocityTracker.clear(); 294 | } 295 | } 296 | 297 | private void initVelocityTrackerIfNotExists() { 298 | if (velocityTracker == null) { 299 | velocityTracker = VelocityTracker.obtain(); 300 | } 301 | } 302 | 303 | private void recycleVelocityTracker() { 304 | if (velocityTracker != null) { 305 | velocityTracker.recycle(); 306 | velocityTracker = null; 307 | } 308 | } 309 | 310 | @Override 311 | protected void onDetachedFromWindow() { 312 | super.onDetachedFromWindow(); 313 | if (scroller != null) { 314 | scroller.abortAnimation(); 315 | scroller = null; 316 | } 317 | removeCallbacks(runnable); 318 | recycleVelocityTracker(); 319 | recyclerView = null; 320 | scrollbar = null; 321 | listener = null; 322 | webView = null; 323 | helper = null; 324 | } 325 | 326 | private void parentFling(float velocityY) { 327 | scroller.fling(0, getScrollY(), 0, (int) velocityY, 0, 0, Integer.MIN_VALUE, Integer.MAX_VALUE); 328 | scroller.computeScrollOffset(); 329 | invalidate(); 330 | } 331 | 332 | @Override 333 | public boolean onStartNestedScroll(@NonNull View child, @NonNull View target, int axes, int type) { 334 | return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0; 335 | } 336 | 337 | @Override 338 | public void onNestedScrollAccepted(@NonNull View view, @NonNull View view1, int axes, int type) { 339 | helper.onNestedScrollAccepted(view, view1, axes, type); 340 | } 341 | 342 | @Override 343 | public int getNestedScrollAxes() { 344 | return helper.getNestedScrollAxes(); 345 | } 346 | 347 | @Override 348 | public boolean onNestedPreFling(@NonNull View target, float velocityX, float velocityY) { 349 | if (target instanceof NestedScrollWebView) { 350 | //WebView滑到底部时,继续向下滑动父控件和RV 351 | currentScrollType = SCROLL_WEB_PARENT; 352 | parentFling(velocityY); 353 | } else if (target instanceof RecyclerView && velocityY < 0 && getScrollY() == maxScrollY) { 354 | //RV滑动到顶部时,继续向上滑动父控件和WebView,这里用于计算到达父控件的顶部时RV的速度 355 | currentScrollType = SCROLL_RV_PARENT; 356 | parentFling((int) velocityY); 357 | } else if (target instanceof RecyclerView && velocityY > 0) { 358 | isRvFlingDown = true; 359 | } 360 | if (Util.isAboveL()) { 361 | return super.onNestedPreFling(target, velocityX, velocityY); 362 | } else { 363 | return false; 364 | } 365 | } 366 | 367 | @Override 368 | public boolean onNestedFling(@NonNull View target, float velocityX, float velocityY, boolean consumed) { 369 | if (Util.isAboveL()) { 370 | return super.onNestedFling(target, velocityX, velocityY, consumed); 371 | } else { 372 | return false; 373 | } 374 | } 375 | 376 | @Override 377 | public void onNestedPreScroll(@NonNull View view, int dx, int dy, @NonNull int[] ints, int type) { 378 | boolean isWebViewBottom = !canWebViewScrollDown(); 379 | boolean isParentCenter = isParentCenter(); 380 | if (dy > 0 && getScrollY() < maxScrollY && isWebViewBottom) { 381 | //为了WebView滑动到底部,继续向下滑动父控件 382 | scrollBy(0, dy); 383 | ints[1] = dy; 384 | } else if (dy < 0 && isParentCenter) { 385 | //为了RecyclerView滑动到顶部时,继续向上滑动父控件 386 | scrollBy(0, dy); 387 | ints[1] = dy; 388 | } 389 | if (isParentCenter && !isWebViewBottom) { 390 | //异常情况的处理 391 | scrollToWebViewBottom(); 392 | } 393 | if (isParentCenter) { 394 | checkRvTop(); 395 | } 396 | } 397 | 398 | @Override 399 | public void onNestedScroll(@NonNull View view, int dxConsumed, int dyConsumed, 400 | int dxUnconsumed, int dyUnconsumed, int type) { 401 | if (dyUnconsumed < 0) { 402 | //RecyclerView向父控件的滑动衔接处 403 | scrollBy(0, dyUnconsumed); 404 | } 405 | if (!isParentCenter()) { 406 | //用于绘制进度条 407 | invalidate(); 408 | } 409 | } 410 | 411 | /** 412 | * 判断连接处的显示 413 | */ 414 | private boolean isParentCenter() { 415 | return getScrollY() > 0 && getScrollY() < webViewHeight; 416 | } 417 | 418 | @Override 419 | public void onStopNestedScroll(@NonNull View view, int i) { 420 | helper.onStopNestedScroll(view); 421 | } 422 | 423 | @Override 424 | public void scrollTo(int x, int y) { 425 | if (y > maxScrollY) { 426 | y = maxScrollY; 427 | } 428 | if (y < 0) { 429 | y = 0; 430 | } 431 | super.scrollTo(x, y); 432 | } 433 | 434 | @Override 435 | public void computeScroll() { 436 | if (scroller.computeScrollOffset()) { 437 | int currY = scroller.getCurrY(); 438 | switch (currentScrollType) { 439 | case SCROLL_SWITCH://上下切换 440 | scrollTo(0, currY); 441 | invalidate(); 442 | isSwitching = !scroller.isFinished(); 443 | if (!isSwitching) { 444 | invalidate();//切换结束,显示一下进度条 445 | } 446 | break; 447 | case SCROLL_WEB_PARENT://WebView向父控件滑动 448 | if (isRvFlingDown) { 449 | //RecyclerView的区域的fling由自己完成 450 | break; 451 | } 452 | scrollTo(0, currY); 453 | invalidate(); 454 | if (isParentCenter()) { 455 | checkRvTop(); 456 | } 457 | if (getScrollY() == maxScrollY && !hasFling && recyclerView != null) { 458 | //滚动到父控件底部,滚动事件交给RecyclerView 459 | hasFling = true; 460 | recyclerView.fling(0, (int) scroller.getCurrVelocity()); 461 | } 462 | break; 463 | case SCROLL_PARENT_WEB://父控件向WebView滑动 464 | scrollTo(0, currY); 465 | invalidate(); 466 | if (currY <= 0 && !hasFling) { 467 | //滚动父控件顶部,滚动事件交给WebView 468 | hasFling = true; 469 | webViewFling((int) -scroller.getCurrVelocity()); 470 | } 471 | break; 472 | case SCROLL_RV_PARENT://RecyclerView向父控件滑动,fling事件,单纯用于计算速度 473 | if (getScrollY() != 0) { 474 | invalidate(); 475 | } else if (!hasFling) { 476 | hasFling = true; 477 | //滑动到顶部时,滚动事件交给WebView 478 | webViewFling((int) -scroller.getCurrVelocity()); 479 | } 480 | break; 481 | } 482 | } 483 | } 484 | 485 | private boolean canWebViewScrollDown() { 486 | if (webView == null) { 487 | return false; 488 | } 489 | final int offset = webView.getScrollY(); 490 | final int range = getWebViewContentHeight() - webView.getHeight(); 491 | if (range == 0) { 492 | return false; 493 | } 494 | return offset < range - 3; 495 | } 496 | 497 | private void scrollToWebViewBottom() { 498 | if (webView != null) { 499 | webView.scrollToBottom(); 500 | } 501 | } 502 | 503 | private void webViewFling(int v) { 504 | webView.flingScroll(0, v); 505 | } 506 | 507 | @Override 508 | protected void onDraw(Canvas canvas) { 509 | if (scrollbar == null && listener == null || webView == null || isSwitching) { 510 | return; 511 | } 512 | int webViewContentHeight = getWebViewContentHeight(); 513 | if (webViewContentHeight == 0) return; 514 | int totalHeight = webViewContentHeight + getRVContentHeight(); 515 | if (totalHeight < getHeight()) { 516 | return; 517 | } 518 | int scrollY = getCurrentScrollY(); 519 | if (scrollbar != null) { 520 | scrollbar.setScrollBar(totalHeight, this.getScrollY(), scrollY); 521 | } 522 | if (listener != null) { 523 | listener.scroll(scrollY); 524 | } 525 | } 526 | 527 | private int getWebViewContentHeight() { 528 | if (webViewContentHeight == 0 && webView != null) { 529 | webViewContentHeight = (int) (webView.getContentHeight() * density); 530 | } 531 | return webViewContentHeight; 532 | } 533 | 534 | private int getRVContentHeight() { 535 | if (recyclerView == null || !isRvShow) { 536 | return 0; 537 | } 538 | if (rvContentHeight == 0 || getScrollY() == maxScrollY) { 539 | //在RecyclerView区域时实时获取内容高度 540 | rvContentHeight = recyclerView.computeVerticalScrollRange(); 541 | } 542 | return rvContentHeight; 543 | } 544 | 545 | private int getRVScrollY() { 546 | if (recyclerView == null || !isRvShow) return 0; 547 | //RecyclerView滑动时再计算滑动距离 548 | if (getScrollY() != maxScrollY) return 0; 549 | return recyclerView.computeVerticalScrollOffset(); 550 | } 551 | 552 | private void isRVShow() { 553 | if (recyclerView == null) { 554 | isRvShow = false; 555 | return; 556 | } 557 | isRvShow = recyclerView.isShown(); 558 | } 559 | 560 | public void setOnScrollListener(onScrollListener listener) { 561 | this.listener = listener; 562 | } 563 | 564 | /** 565 | * 获取当前的滑动距离 566 | */ 567 | public int getCurrentScrollY() { 568 | if (webView == null) return 0; 569 | int wbScrollY = getWebViewScrollY(); 570 | if (maxScrollY != 0 && getScrollY() == maxScrollY) { 571 | wbScrollY = getWebViewContentHeight() - webView.getHeight(); 572 | } 573 | return getScrollY() + wbScrollY + getRVScrollY(); 574 | } 575 | 576 | /** 577 | * 获取当前WebView的滑动距离 578 | */ 579 | public int getWebViewScrollY() { 580 | return webView.getScrollY(); 581 | } 582 | 583 | /** 584 | * 如果WebView为MatchParent并且内容存在不满一屏的情况,需要手动设置WebView的内容高度 585 | * 如果WebView为WrapContent时,通常并不需要,如果存在高度不准确的情况,可以手动设置 586 | * WebView的内容高度可让前端同学通过js传递给你 587 | */ 588 | public void setWebViewContentHeight(int contentHeight) { 589 | int height = getMeasuredHeight(); 590 | if (contentHeight > 0 && height > 0) { 591 | rvScrollToPosition(0); 592 | //手动设置的WebView内容高度不为0时,重新布局页面 593 | webViewHeight = contentHeight; 594 | if (webViewHeight >= height) { 595 | webViewHeight = height; 596 | resetWebViewHeight(LayoutParams.MATCH_PARENT); 597 | } else { 598 | resetWebViewHeight(webViewHeight); 599 | } 600 | super.requestLayout(); 601 | } 602 | } 603 | 604 | private void resetWebViewHeight(int height) { 605 | if (webView != null) { 606 | ViewGroup.LayoutParams params = webView.getLayoutParams(); 607 | params.height = height; 608 | webView.setLayoutParams(params); 609 | } 610 | } 611 | 612 | /** 613 | * 滚动到某个位置 614 | */ 615 | public void scrollToPosition(int y) { 616 | if (webView == null) return; 617 | int webViewContentHeight = getWebViewContentHeight(); 618 | if (webViewContentHeight == 0) return; 619 | int webH = webViewContentHeight - webViewHeight; 620 | if (y <= webH) { 621 | webView.scrollTo(0, y); 622 | } else if (y <= webH + webViewHeight) { 623 | scrollToWebViewBottom(); 624 | scrollTo(0, y - webH); 625 | } else { 626 | scrollToWebViewBottom(); 627 | scrollTo(0, webViewHeight); 628 | } 629 | } 630 | 631 | /** 632 | * WebView和RecyclerView的上下切换 633 | * 634 | * @param rvPosition 切换到RecyclerView时需要定位到的位置 635 | */ 636 | public void switchView(int rvPosition) { 637 | if (isSwitching || maxScrollY == 0) { 638 | return; 639 | } 640 | isSwitching = true; 641 | resetScroller(); 642 | currentScrollType = SCROLL_SWITCH; 643 | if (getScrollY() == 0) {//滑向Bottom 644 | if (maxScrollY != getHeight()) { 645 | //向下切换时,如果rv的高度不足一屏,那么切换到rv时会处于连接处,需要将WebView滑动到底部 646 | scrollToWebViewBottom(); 647 | } 648 | rvScrollToPosition(rvPosition); 649 | scroller.startScroll(0, 0, 0, maxScrollY, switchDuration); 650 | } else if (getScrollY() == maxScrollY) {//滑向Top 651 | if (webViewHeight < getHeight()) { 652 | rvScrollToPosition(0); 653 | } 654 | scroller.startScroll(0, maxScrollY, 0, -maxScrollY, switchDuration); 655 | } else {//在交界处优先滑向Top 656 | if (webViewHeight < getHeight()) { 657 | rvScrollToPosition(0); 658 | } 659 | scroller.startScroll(0, getScrollY(), 0, -getScrollY(), switchDuration); 660 | } 661 | scroller.computeScrollOffset(); 662 | invalidate(); 663 | } 664 | 665 | private void rvScrollToPosition(int position) { 666 | if (recyclerView == null) return; 667 | recyclerView.scrollToPosition(position); 668 | RecyclerView.LayoutManager manager = recyclerView.getLayoutManager(); 669 | if (manager instanceof LinearLayoutManager) { 670 | ((LinearLayoutManager) manager).scrollToPositionWithOffset(position, 0); 671 | } 672 | } 673 | 674 | /** 675 | * 当父控件有偏移时,检查RecyclerView是否在顶部 676 | */ 677 | private void checkRvTop() { 678 | if (isRvNotTop()) { 679 | rvScrollToPosition(0); 680 | } 681 | } 682 | 683 | private boolean isRvNotTop() { 684 | if (recyclerView == null) return true; 685 | return recyclerView.canScrollVertically(-1); 686 | } 687 | 688 | /** 689 | * 处理未知的错误情况 690 | */ 691 | private void fixError() { 692 | //当父控件有偏移,但是WebView却不在底部时,或者RecyclerView不在顶部时,属于异常情况,进行修复 693 | //目前的测试中没有出现这种异常,此代码作为异常防御 694 | if (isParentCenter()) { 695 | if (canWebViewScrollDown()) { 696 | scrollToWebViewBottom(); 697 | } 698 | if (isRvNotTop()) { 699 | rvScrollToPosition(0); 700 | } 701 | } 702 | } 703 | 704 | 705 | } 706 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/java/com/hzw/nested/ScrollBarView.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested; 2 | 3 | import android.content.Context; 4 | import android.graphics.Canvas; 5 | import android.graphics.Paint; 6 | import android.os.Handler; 7 | import android.os.Message; 8 | import android.support.annotation.Nullable; 9 | import android.util.AttributeSet; 10 | import android.view.View; 11 | 12 | import java.lang.ref.WeakReference; 13 | 14 | /** 15 | * author: hzw 16 | * time: 2019/3/5 下午3:13 17 | * description:{@link NestedWebViewRecyclerViewGroup}的ScrollBar 18 | */ 19 | class ScrollBarView extends View { 20 | 21 | private final static int ALPHA_OFFSET = 30; 22 | private final static int MSG_WHAT = 1314; 23 | private final static int DURATION = 300; 24 | private Paint paint = new Paint(); 25 | private BarHandler handler; 26 | private int minBarHeight; 27 | private int barWidth; 28 | private int center; 29 | private int space; 30 | private int measureHeight; 31 | private int barHeight; 32 | private int barOffset; 33 | private int alpha; 34 | private boolean isClearBar; 35 | private boolean scrollOver; 36 | 37 | public ScrollBarView(Context context) { 38 | this(context, null); 39 | } 40 | 41 | public ScrollBarView(Context context, @Nullable AttributeSet attrs) { 42 | this(context, attrs, 0); 43 | } 44 | 45 | public ScrollBarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 46 | super(context, attrs, defStyleAttr); 47 | paint.setAntiAlias(true); 48 | paint.setStrokeCap(Paint.Cap.ROUND); 49 | handler = new BarHandler(this); 50 | } 51 | 52 | void init(int color, int space, int barWidth, int minBarHeight) { 53 | //ScrollBar颜色 54 | paint.setColor(color); 55 | //ScrollBar距离屏幕右边的距离 56 | this.space = space; 57 | //ScrollBar粗细 58 | this.barWidth = barWidth; 59 | //ScrollBar最小高度 60 | this.minBarHeight = minBarHeight; 61 | //绘制水平中心点 62 | center = barWidth / 2; 63 | paint.setStrokeWidth(barWidth); 64 | } 65 | 66 | @Override 67 | protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 68 | super.onMeasure(widthMeasureSpec, heightMeasureSpec); 69 | int h = MeasureSpec.getSize(heightMeasureSpec); 70 | setMeasuredDimension(barWidth + space, h); 71 | measureHeight = h; 72 | } 73 | 74 | void setScrollBar(int contentHeight, int parentScrollY, int childScrollY) { 75 | if (contentHeight == 0) return; 76 | isClearBar = false; 77 | scrollOver = false; 78 | alpha = 255; 79 | //计算scrollBar的高度 80 | barHeight = measureHeight * measureHeight / contentHeight; 81 | barHeight = barHeight < minBarHeight ? minBarHeight : barHeight; 82 | //计算scrollBar的偏移量 83 | barOffset = parentScrollY + barWidth / 2 + 84 | childScrollY * (measureHeight - barHeight - barWidth) / (contentHeight - measureHeight); 85 | invalidate(); 86 | } 87 | 88 | @Override 89 | protected void onDraw(Canvas canvas) { 90 | super.onDraw(canvas); 91 | if (!isClearBar) { 92 | paint.setAlpha(alpha); 93 | canvas.drawLine(center, barOffset, center, barOffset + barHeight, paint); 94 | clearScrollBar(); 95 | } 96 | } 97 | 98 | private void clearScrollBar() { 99 | if (!scrollOver) { 100 | handler.removeMessages(MSG_WHAT); 101 | handler.sendEmptyMessageDelayed(MSG_WHAT, DURATION); 102 | } 103 | } 104 | 105 | private static class BarHandler extends Handler { 106 | private WeakReference reference; 107 | 108 | BarHandler(ScrollBarView barView) { 109 | reference = new WeakReference<>(barView); 110 | } 111 | 112 | @Override 113 | public void handleMessage(Message msg) { 114 | ScrollBarView barView = reference.get(); 115 | if (barView != null) { 116 | barView.scrollOver = true; 117 | barView.alpha -= ALPHA_OFFSET; 118 | barView.alpha = barView.alpha < 0 ? 0 : barView.alpha; 119 | if (barView.alpha == 0) { 120 | barView.isClearBar = true; 121 | } else { 122 | sendEmptyMessageDelayed(MSG_WHAT, 10); 123 | } 124 | barView.invalidate(); 125 | } 126 | } 127 | } 128 | 129 | @Override 130 | protected void onDetachedFromWindow() { 131 | super.onDetachedFromWindow(); 132 | if (handler != null) { 133 | handler.removeCallbacksAndMessages(null); 134 | handler = null; 135 | } 136 | } 137 | 138 | 139 | } 140 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/java/com/hzw/nested/Util.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested; 2 | 3 | import android.content.res.Resources; 4 | import android.os.Build; 5 | 6 | /** 7 | * author: hzw 8 | * time: 2019/4/8 下午5:03 9 | * description:util 10 | */ 11 | class Util { 12 | static int dip2px(float dipValue) { 13 | final float scale = Resources.getSystem().getDisplayMetrics().density; 14 | return (int) (dipValue * scale + 0.5f); 15 | } 16 | 17 | /** 18 | * @return 系统版本是否高于Android 5.0(API 21) 19 | */ 20 | static boolean isAboveL() { 21 | return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/java/com/hzw/nested/onScrollListener.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested; 2 | 3 | /** 4 | * author: hzw 5 | * time: 2019/3/27 下午3:08 6 | * description:滑动监听 7 | */ 8 | public interface onScrollListener { 9 | void scroll(int y); 10 | } 11 | -------------------------------------------------------------------------------- /NestedWebViewRecyclerViewGroup/src/main/res/values/attr.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NestedWebViewRecyclerViewGroup 2 | 3 | [ ![Download](https://api.bintray.com/packages/hzwsunshine/maven/NestedWebViewRecyclerViewGroup/images/download.svg) ](https://bintray.com/hzwsunshine/maven/NestedWebViewRecyclerViewGroup/_latestVersion) 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | 6 | NestedWebViewRecyclerViewGroup 是 WebView 和 RecyclerView 的嵌套控件,用于经典的上面是 WebView 显示的文章,下面是 RecyclerView 显示的评论的文章详情页结构中,可以实现 WebView 和 RecyclerView 的无缝滑动切换,也提供 WebView 区域和 RecyclerView 区域的上下显示切换。
7 | NestedWebViewRecyclerViewGroup 的控件高度为该控件的屏幕可见高度,内容高度为 WebView 的控件高度和 RecyclerView 的控件高度之和,占用内存小,滑动流畅。 8 | 9 | 相关技术点参考:[NestedScrolling:文章详情页的实现](https://blog.csdn.net/hzwailll/article/details/89854692) 10 | 11 | ![image](https://github.com/HzwSunshine/NestedWebViewRecyclerViewGroup/blob/master/app/example/example.gif) 12 | 13 |
14 | 15 | ## Gradle 16 | 17 | compile 'com.github.hzw:NestedWebViewRecyclerViewGroup:'DownLoad Version'' 18 | 19 | 所需依赖:com.android.support:support-v4:xxx 20 | com.android.support:recyclerview-v7:xxx 21 | 22 |
23 | 24 | ## 使用 25 | 26 | **为了使用方便定义了以下一些属性**: 27 | ```xml 28 | //WebView和RecyclerView上下切换的时间 29 | 30 | //scrollbar是否可用 31 | 32 | //scrollbar的颜色 33 | 34 | //scrollbar的最小高度 35 | 36 | //scrollbar的宽度 37 | 38 | //scrollbar距离屏幕右边的距离 39 | 40 | ``` 41 | 42 | 43 | **xml** 44 | 45 | ```xml 46 | 52 | 53 | 56 | 57 | 58 | 61 | 62 | 63 | 64 | 65 | *** 66 | <也支持动态的添加 NestedScrollWebView 和 RecyclerView,具体请查看Demo> 67 | *** 68 | <也可以只添加 NestedScrollWebView 或者它的Parent> 69 | ``` 70 | 71 | 72 | **code** 73 | 74 | ```java 75 | //如果WebView为MatchParent并且内容存在不满一屏的情况,需要手动设置WebView的内容高度 76 | //如果WebView为WrapContent时,通常不需要设置,如果存在高度不准确的情况,可以手动设置 77 | //WebView的内容高度可让前端同学通过js传递给你 78 | setWebViewContentHeight(int height) ; 79 | 80 | //设置滑动监听 81 | setOnScrollListener(onScrollListener listener) 82 | 83 | //获取当前的滑动距离 84 | getCurrentScrollY() 85 | 86 | //获取WebView的滑动距离 87 | getWebViewScrollY() 88 | 89 | //定位到指定的位置 90 | scrollToPosition(int y) 91 | 92 | //WebView和RecyclerView区域的上下切换 93 | switchView(int rvPosition) 94 | 95 | 96 | //当你的 RecyclerView 不在当前布局中时,有两种方式可以将 RecyclerView 97 | //和 NestedWebViewRecyclerViewGroup 关联起来 98 | 99 | //1. 在 NestedWebViewRecyclerViewGroup 的内部如果在解析布局文件时,如果没有找到 RecyclerView , 100 | //那么在界面显示时会尝试再次获取 RecyclerView ,这种情况不需要你再做额外的事情,通常情况下不需要此设置 101 | 102 | //2. 如果你还有更特殊的用法,情况1 任然没有找到你的 RecyclerView 103 | //那么可以调用setRecyclerView 方法,将两者关联 104 | setRecyclerView(RecyclerView recyclerView) 105 | ``` 106 | 107 | 108 | 109 | **使用时请注意**: 110 | 1. NestedWebViewRecyclerViewGroup 最多只能包含两个子View: NestedScrollWebView 111 | 和 RecyclerView 或包含它们两者的ViewGroup,具体可查看Demo 112 | 113 | 2. RecyclerView 或它的ViewGroup是非必须的 114 | 115 | 116 |

117 | 118 | License 119 | ------- 120 | 121 | Copyright 2019 hzwSunshine 122 | 123 | Licensed under the Apache License, Version 2.0 (the "License"); 124 | you may not use this file except in compliance with the License. 125 | You may obtain a copy of the License at 126 | 127 | http://www.apache.org/licenses/LICENSE-2.0 128 | 129 | Unless required by applicable law or agreed to in writing, software 130 | distributed under the License is distributed on an "AS IS" BASIS, 131 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 132 | See the License for the specific language governing permissions and 133 | limitations under the License. 134 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | applicationId "com.hzw.nestedviewgroup.example" 7 | minSdkVersion 17 8 | targetSdkVersion 28 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | } 20 | 21 | dependencies { 22 | implementation fileTree(include: ['*.jar'], dir: 'libs') 23 | implementation 'com.android.support:appcompat-v7:28.0.0' 24 | implementation 'com.android.support.constraint:constraint-layout:1.1.3' 25 | implementation 'com.android.support:support-v4:28.0.0' 26 | testImplementation 'junit:junit:4.12' 27 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 28 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 29 | implementation project(':NestedWebViewRecyclerViewGroup') 30 | implementation 'com.android.support:recyclerview-v7:28.0.0' 31 | } 32 | -------------------------------------------------------------------------------- /app/example/example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HzwSunshine/NestedWebViewRecyclerViewGroup/66e06452e7928475de37bbe007a9d53a9818c5c6/app/example/example.gif -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/hzw/nested/example/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.hzw.nestedviewgroup.example", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 31 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/CommentFragment.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | 4 | import android.os.Bundle; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | import android.support.v4.app.Fragment; 8 | import android.support.v7.widget.LinearLayoutManager; 9 | import android.support.v7.widget.RecyclerView; 10 | import android.view.LayoutInflater; 11 | import android.view.View; 12 | import android.view.ViewGroup; 13 | 14 | 15 | /** 16 | * A simple {@link Fragment} subclass. 17 | */ 18 | public class CommentFragment extends Fragment { 19 | 20 | private RecyclerView recyclerView; 21 | private RvAdapter adapter; 22 | 23 | @Override 24 | public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, 25 | Bundle savedInstanceState) { 26 | return inflater.inflate(R.layout.fragment_comment, container, false); 27 | } 28 | 29 | @Override 30 | public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { 31 | super.onViewCreated(view, savedInstanceState); 32 | recyclerView = view.findViewById(R.id.recyclerView); 33 | LinearLayoutManager manager = new LinearLayoutManager(getActivity()); 34 | manager.setOrientation(LinearLayoutManager.VERTICAL); 35 | recyclerView.setLayoutManager(manager); 36 | adapter = new RvAdapter(true); 37 | recyclerView.setAdapter(adapter); 38 | } 39 | 40 | public RecyclerView getRecyclerView() { 41 | return recyclerView; 42 | } 43 | 44 | public void addItem() { 45 | adapter.addItem(); 46 | } 47 | 48 | public void deleteItem() { 49 | adapter.deleteItem(); 50 | } 51 | 52 | public void hide(){ 53 | if (recyclerView.getVisibility() == View.VISIBLE) { 54 | recyclerView.setVisibility(View.GONE); 55 | } else { 56 | recyclerView.setVisibility(View.VISIBLE); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/CustomerWebView.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.util.AttributeSet; 6 | import android.webkit.WebChromeClient; 7 | import android.webkit.WebViewClient; 8 | 9 | import com.hzw.nested.NestedScrollWebView; 10 | 11 | /** 12 | * author: hzw 13 | * time: 2019-05-08 19:35 14 | * description:自定义的WebView 15 | */ 16 | public class CustomerWebView extends NestedScrollWebView { 17 | public CustomerWebView(Context context) { 18 | super(context); 19 | init(); 20 | } 21 | 22 | public CustomerWebView(Context context, AttributeSet attrs) { 23 | super(context, attrs); 24 | init(); 25 | } 26 | 27 | public CustomerWebView(Context context, AttributeSet attrs, int defStyleAttr) { 28 | super(context, attrs, defStyleAttr); 29 | init(); 30 | } 31 | 32 | @SuppressLint("SetJavaScriptEnabled") 33 | private void init() { 34 | setVerticalScrollBarEnabled(false); 35 | setHorizontalScrollBarEnabled(false); 36 | getSettings().setJavaScriptEnabled(true); 37 | setWebViewClient(new WebViewClient()); 38 | setWebChromeClient(new WebChromeClient()); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/Entity.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | /** 4 | * author: hzw 5 | * time: 2019/4/8 下午7:04 6 | * description: 7 | */ 8 | public class Entity { 9 | public static final int COMMENT = 0; 10 | public static final int ABOUT = 1; 11 | public static final int DIVIDER = 2; 12 | public static final int IMAGE = 3; 13 | int type; 14 | String title; 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.view.View; 7 | import android.widget.Button; 8 | 9 | public class MainActivity extends AppCompatActivity { 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | setContentView(R.layout.activity_main); 15 | initView(); 16 | } 17 | 18 | private void initView() { 19 | Button nested = findViewById(R.id.nested); 20 | Button nestedFragment = findViewById(R.id.nested_fragment); 21 | Button wrapRv = findViewById(R.id.wrap_rv); 22 | nested.setOnClickListener(new View.OnClickListener() { 23 | @Override 24 | public void onClick(View v) { 25 | startActivity(new Intent(MainActivity.this, NestedActivity.class)); 26 | } 27 | }); 28 | nestedFragment.setOnClickListener(new View.OnClickListener() { 29 | @Override 30 | public void onClick(View v) { 31 | startActivity(new Intent(MainActivity.this, NestedFragmentActivity.class)); 32 | } 33 | }); 34 | wrapRv.setOnClickListener(new View.OnClickListener() { 35 | @Override 36 | public void onClick(View v) { 37 | startActivity(new Intent(MainActivity.this, WrapRvActivity.class)); 38 | } 39 | }); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/NestedActivity.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.view.View; 9 | import android.webkit.WebChromeClient; 10 | import android.webkit.WebView; 11 | import android.webkit.WebViewClient; 12 | import android.widget.TextView; 13 | 14 | import com.hzw.nested.NestedWebViewRecyclerViewGroup; 15 | 16 | public class NestedActivity extends AppCompatActivity implements View.OnClickListener { 17 | 18 | private NestedWebViewRecyclerViewGroup parent; 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_nested); 24 | //RecyclerView recyclerView = findViewById(R.id.nest_rv); 25 | parent = findViewById(R.id.nest_parent); 26 | TextView tvComment = findViewById(R.id.tv_comment); 27 | TextView tvLastRead = findViewById(R.id.tv_last_read); 28 | tvComment.setOnClickListener(this); 29 | tvLastRead.setOnClickListener(this); 30 | LinearLayoutManager manager = new LinearLayoutManager(this); 31 | manager.setOrientation(LinearLayoutManager.VERTICAL); 32 | // recyclerView.setLayoutManager(manager); 33 | // recyclerView.setAdapter(new RvAdapter()); 34 | initWebView(); 35 | } 36 | 37 | @Override 38 | public void onStop() { 39 | super.onStop(); 40 | int scrollY = parent.getCurrentScrollY(); 41 | ReadUtil.saveRead(this, scrollY); 42 | } 43 | 44 | @SuppressLint("SetJavaScriptEnabled") 45 | private void initWebView() { 46 | WebView webView = findViewById(R.id.nest_webView); 47 | webView.setVerticalScrollBarEnabled(false); 48 | webView.setHorizontalScrollBarEnabled(false); 49 | webView.getSettings().setJavaScriptEnabled(true); 50 | webView.setWebViewClient(new WebViewClient()); 51 | webView.setWebChromeClient(new WebChromeClient()); 52 | webView.loadUrl("https://github.com/HzwSunshine/NestedWebViewRecyclerViewGroup"); 53 | } 54 | 55 | @Override 56 | public void onClick(View v) { 57 | switch (v.getId()) { 58 | case R.id.tv_comment: 59 | parent.switchView(7); 60 | break; 61 | case R.id.tv_last_read: 62 | int last = ReadUtil.getRead(this); 63 | parent.scrollToPosition(last); 64 | break; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/NestedFragmentActivity.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.os.Bundle; 4 | import android.support.v4.app.FragmentManager; 5 | import android.support.v4.app.FragmentTransaction; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.util.Log; 9 | import android.view.View; 10 | import android.webkit.WebView; 11 | import android.widget.FrameLayout; 12 | import android.widget.TextView; 13 | 14 | import com.hzw.nested.NestedWebViewRecyclerViewGroup; 15 | 16 | public class NestedFragmentActivity extends AppCompatActivity implements View.OnClickListener { 17 | 18 | private NestedWebViewRecyclerViewGroup parent; 19 | private CommentFragment fragment; 20 | 21 | @Override 22 | protected void onCreate(Bundle savedInstanceState) { 23 | super.onCreate(savedInstanceState); 24 | setContentView(R.layout.activity_nested_fragment); 25 | parent = findViewById(R.id.nest_parent); 26 | TextView tvComment = findViewById(R.id.tv_comment); 27 | TextView addItem = findViewById(R.id.addItem); 28 | TextView deleteItem = findViewById(R.id.deleteItem); 29 | tvComment.setOnClickListener(this); 30 | addItem.setOnClickListener(this); 31 | deleteItem.setOnClickListener(this); 32 | findViewById(R.id.hide_rv).setOnClickListener(this); 33 | initWebView(); 34 | 35 | //评论是一个以Fragment的方式存在 36 | FragmentManager manager = getSupportFragmentManager(); 37 | fragment = (CommentFragment) manager.findFragmentByTag(CommentFragment.class.getName()); 38 | FragmentTransaction transaction = manager.beginTransaction(); 39 | if (fragment == null) { 40 | fragment = new CommentFragment(); 41 | transaction.add(R.id.fragment_container, fragment, CommentFragment.class.getName()); 42 | } else { 43 | transaction.attach(fragment); 44 | } 45 | transaction.commit(); 46 | 47 | 48 | //当你的评论的 RecyclerView 在一个Fragment中时,有两种方式可以将 RecyclerView 49 | //和 NestedWebViewRecyclerViewGroup 关联起来 50 | 51 | //1. 在 NestedWebViewRecyclerViewGroup 的内部如果在解析布局文件时,如果没有找到 RecyclerView , 52 | //那么在界面显示时会尝试重新获取 RecyclerView ,这种情况不需要你再做额外的事情 53 | 54 | //2. 如果你还有更特殊的用法,当 NestedWebViewRecyclerViewGroup 在界面显示时都无法获取到 RecyclerView 55 | //那么可以调用 NestedWebViewRecyclerViewGroup 的 setRecyclerView 方法,将两者关联 56 | //parent.setRecyclerView(your recyclerView); 57 | 58 | parent.post(new Runnable() { 59 | @Override 60 | public void run() { 61 | Log.i("xxx", "run: parent"); 62 | } 63 | }); 64 | } 65 | 66 | @Override 67 | public void onStop() { 68 | super.onStop(); 69 | int scrollY = parent.getCurrentScrollY(); 70 | ReadUtil.saveRead(this, scrollY); 71 | } 72 | 73 | private void initWebView() { 74 | //手动添加WebView的方式,便于WebView的复用以及其他 75 | WebView webView = new CustomerWebView(this); 76 | FrameLayout container = findViewById(R.id.webView_container); 77 | container.addView(webView); 78 | webView.loadUrl("https://github.com/HzwSunshine/NestedWebViewRecyclerViewGroup"); 79 | } 80 | 81 | @Override 82 | public void onClick(View v) { 83 | switch (v.getId()) { 84 | case R.id.tv_comment: 85 | parent.switchView(0); 86 | break; 87 | case R.id.addItem: 88 | fragment.addItem(); 89 | break; 90 | case R.id.deleteItem: 91 | fragment.deleteItem(); 92 | break; 93 | case R.id.hide_rv: 94 | View view = findViewById(R.id.fragment_container); 95 | if (view.getVisibility() == View.VISIBLE) { 96 | view.setVisibility(View.GONE); 97 | } else { 98 | view.setVisibility(View.VISIBLE); 99 | } 100 | break; 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/ReadUtil.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | public class ReadUtil { 7 | 8 | private static final String FILE_NAME = "NestedViewGroup"; 9 | private static final String READ_KEY = "nested_read"; 10 | 11 | 12 | public static void saveRead(Context context, int position) { 13 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 14 | SharedPreferences.Editor editor = sp.edit(); 15 | editor.putInt(READ_KEY, position); 16 | editor.apply(); 17 | } 18 | 19 | 20 | public static int getRead(Context context) { 21 | SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE); 22 | return sp.getInt(READ_KEY, 0); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/RvAdapter.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.view.LayoutInflater; 6 | import android.view.View; 7 | import android.view.ViewGroup; 8 | import android.widget.TextView; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * author: hzw 15 | * time: 2019/4/8 下午7:03 16 | * description: 17 | */ 18 | public class RvAdapter extends RecyclerView.Adapter { 19 | 20 | private List list = new ArrayList<>(); 21 | 22 | RvAdapter() { 23 | Entity image = new Entity(); 24 | image.type = Entity.IMAGE; 25 | list.add(image); 26 | 27 | Entity title = new Entity(); 28 | title.type = Entity.DIVIDER; 29 | title.title = "相关描述"; 30 | list.add(title); 31 | 32 | for (int i = 0; i < 5; i++) { 33 | Entity entity = new Entity(); 34 | entity.type = Entity.ABOUT; 35 | entity.title = String.format("%s. 相关描述:这是一个RecyclerView和WebView的嵌套控件", i + 1); 36 | list.add(entity); 37 | } 38 | 39 | Entity title2 = new Entity(); 40 | title2.type = Entity.DIVIDER; 41 | title2.title = "评论区"; 42 | list.add(title2); 43 | 44 | for (int i = 0; i < 8; i++) { 45 | Entity entity2 = new Entity(); 46 | entity2.type = Entity.COMMENT; 47 | entity2.title = String.format("%s. NestedWebViewRecyclerViewGroup一个RecyclerView和WebView的嵌套控件,一般用于文章详情页的结构中,解决RecyclerView和WebView滑动时的无缝衔接!", i + 1); 48 | list.add(entity2); 49 | } 50 | } 51 | 52 | RvAdapter(boolean wrap) { 53 | for (int i = 0; i < 2; i++) { 54 | Entity entity2 = new Entity(); 55 | entity2.type = Entity.COMMENT; 56 | entity2.title = String.format("%s. NestedWebViewRecyclerViewGroup一个RecyclerView和WebView的嵌套控件,一般用于文章详情页的结构中,解决RecyclerView和WebView滑动时的无缝衔接!", i + 1); 57 | list.add(entity2); 58 | } 59 | } 60 | 61 | public void addItem() { 62 | Entity entity2 = new Entity(); 63 | entity2.type = Entity.COMMENT; 64 | entity2.title = "NestedWebViewRecyclerViewGroup一个RecyclerView和WebView的嵌套控件,一般用于文章详情页的结构中,解决RecyclerView和WebView滑动时的无缝衔接!xxxx"; 65 | list.add(0, entity2); 66 | notifyItemInserted(0); 67 | } 68 | 69 | public void deleteItem() { 70 | if (list.size() > 0) { 71 | list.remove(0); 72 | notifyItemRemoved(0); 73 | } 74 | } 75 | 76 | @NonNull 77 | @Override 78 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { 79 | LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); 80 | switch (viewType) { 81 | case Entity.IMAGE: 82 | return new ImageHolder(inflater.inflate(R.layout.item_image, viewGroup, false)); 83 | case Entity.ABOUT: 84 | return new AboutHolder(inflater.inflate(R.layout.item_about, viewGroup, false)); 85 | case Entity.COMMENT: 86 | return new CommentHolder(inflater.inflate(R.layout.item_comment, viewGroup, false)); 87 | case Entity.DIVIDER: 88 | default: 89 | return new DividerHolder(inflater.inflate(R.layout.item_divider, viewGroup, false)); 90 | } 91 | } 92 | 93 | @Override 94 | public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) { 95 | switch (getItemViewType(i)) { 96 | case Entity.ABOUT: 97 | AboutHolder aboutHolder = (AboutHolder) holder; 98 | aboutHolder.title.setText(list.get(i).title); 99 | break; 100 | case Entity.COMMENT: 101 | CommentHolder commentHolder = (CommentHolder) holder; 102 | commentHolder.comment.setText(list.get(i).title); 103 | break; 104 | case Entity.DIVIDER: 105 | DividerHolder dividerHolder = (DividerHolder) holder; 106 | dividerHolder.title.setText(list.get(i).title); 107 | break; 108 | } 109 | } 110 | 111 | @Override 112 | public int getItemCount() { 113 | return list.size(); 114 | } 115 | 116 | @Override 117 | public int getItemViewType(int position) { 118 | return list.get(position).type; 119 | } 120 | 121 | private static class AboutHolder extends RecyclerView.ViewHolder { 122 | 123 | private TextView title; 124 | 125 | AboutHolder(@NonNull View itemView) { 126 | super(itemView); 127 | title = itemView.findViewById(R.id.about_title); 128 | } 129 | } 130 | 131 | private static class DividerHolder extends RecyclerView.ViewHolder { 132 | 133 | private TextView title; 134 | 135 | DividerHolder(@NonNull View itemView) { 136 | super(itemView); 137 | title = itemView.findViewById(R.id.title_text); 138 | } 139 | } 140 | 141 | private static class CommentHolder extends RecyclerView.ViewHolder { 142 | 143 | private TextView comment; 144 | 145 | CommentHolder(@NonNull View itemView) { 146 | super(itemView); 147 | comment = itemView.findViewById(R.id.comment_text); 148 | } 149 | } 150 | 151 | private static class ImageHolder extends RecyclerView.ViewHolder { 152 | 153 | ImageHolder(@NonNull View itemView) { 154 | super(itemView); 155 | } 156 | } 157 | 158 | 159 | } 160 | -------------------------------------------------------------------------------- /app/src/main/java/com/hzw/nested/example/WrapRvActivity.java: -------------------------------------------------------------------------------- 1 | package com.hzw.nested.example; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.view.View; 9 | import android.webkit.WebChromeClient; 10 | import android.webkit.WebView; 11 | import android.webkit.WebViewClient; 12 | import android.widget.TextView; 13 | 14 | import com.hzw.nested.NestedWebViewRecyclerViewGroup; 15 | 16 | public class WrapRvActivity extends AppCompatActivity implements View.OnClickListener { 17 | 18 | private NestedWebViewRecyclerViewGroup parent; 19 | private RvAdapter adapter; 20 | private RecyclerView recyclerView; 21 | 22 | @Override 23 | protected void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | setContentView(R.layout.activity_wrap_rv); 26 | recyclerView = findViewById(R.id.nest_rv); 27 | parent = findViewById(R.id.nest_parent); 28 | TextView tvComment = findViewById(R.id.tv_comment); 29 | TextView addItem = findViewById(R.id.addItem); 30 | TextView deleteItem = findViewById(R.id.deleteItem); 31 | tvComment.setOnClickListener(this); 32 | addItem.setOnClickListener(this); 33 | deleteItem.setOnClickListener(this); 34 | findViewById(R.id.hide_rv).setOnClickListener(this); 35 | findViewById(R.id.tv_height).setOnClickListener(this); 36 | LinearLayoutManager manager = new LinearLayoutManager(this); 37 | manager.setOrientation(LinearLayoutManager.VERTICAL); 38 | recyclerView.setLayoutManager(manager); 39 | adapter = new RvAdapter(true); 40 | recyclerView.setAdapter(adapter); 41 | initWebView(); 42 | } 43 | 44 | @SuppressLint("SetJavaScriptEnabled") 45 | private void initWebView() { 46 | WebView webView = findViewById(R.id.nest_webView); 47 | webView.setVerticalScrollBarEnabled(false); 48 | webView.setHorizontalScrollBarEnabled(false); 49 | webView.getSettings().setJavaScriptEnabled(true); 50 | webView.setWebViewClient(new WebViewClient()); 51 | webView.setWebChromeClient(new WebChromeClient()); 52 | webView.loadUrl("https://www.cnblogs.com/xxxxxx.html"); 53 | } 54 | 55 | @Override 56 | public void onClick(View v) { 57 | switch (v.getId()) { 58 | case R.id.tv_comment: 59 | parent.switchView(0); 60 | break; 61 | case R.id.addItem: 62 | adapter.addItem(); 63 | break; 64 | case R.id.deleteItem: 65 | adapter.deleteItem(); 66 | break; 67 | case R.id.hide_rv: 68 | if (recyclerView.getVisibility() == View.VISIBLE) { 69 | recyclerView.setVisibility(View.GONE); 70 | } else { 71 | recyclerView.setVisibility(View.VISIBLE); 72 | } 73 | break; 74 | case R.id.tv_height: 75 | View change = findViewById(R.id.changeView); 76 | if (change.getVisibility() == View.VISIBLE) { 77 | change.setVisibility(View.GONE); 78 | } else { 79 | change.setVisibility(View.VISIBLE); 80 | } 81 | break; 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 |