├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── yuyang │ │ └── library │ │ ├── ChildAdapter.java │ │ ├── MainActivity.java │ │ ├── ParentAdapter.java │ │ ├── TabViewHolder.java │ │ └── nested │ │ ├── MainActivityWithoutTab.java │ │ └── ParentAdapterWithoutTab.java │ └── res │ ├── layout │ ├── activity_main.xml │ ├── activity_main_without_tab.xml │ └── layout_inner.xml │ ├── menu │ └── menu_main.xml │ ├── mipmap-xxxhdpi │ ├── ic_launcher.webp │ ├── ic_launcher_round.webp │ ├── p1.png │ ├── p2.png │ └── p3.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── themes.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── yuyang │ └── library │ └── nestedrv │ ├── ChildRecyclerView.java │ ├── INestedParentAdapter.java │ ├── NestedOverScroller.java │ └── ParentRecyclerView.java ├── record.gif ├── record.mp4 ├── screenshot.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea 4 | /local.properties 5 | /.idea/caches 6 | /.idea/libraries 7 | /.idea/modules.xml 8 | /.idea/workspace.xml 9 | /.idea/navEditor.xml 10 | /.idea/assetWizardSettings.xml 11 | .DS_Store 12 | /build 13 | /captures 14 | .externalNativeBuild 15 | .cxx 16 | local.properties 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## NestedRecyclerView 2 | 3 | RecyclerView 嵌套 多Tab 吸顶容器,类似 朴朴超市 首页。 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | namespace 'com.yuyang.library' 7 | compileSdk 28 8 | 9 | defaultConfig { 10 | applicationId "com.yuyang.library" 11 | minSdk 23 12 | targetSdk 28 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | vectorDrawables { 17 | useSupportLibrary true 18 | } 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_1_8 29 | targetCompatibility JavaVersion.VERSION_1_8 30 | } 31 | 32 | buildFeatures { 33 | compose true 34 | } 35 | } 36 | 37 | dependencies { 38 | implementation fileTree(dir: 'libs', include: ['*.jar']) 39 | 40 | implementation 'com.android.support:appcompat-v7:28.0.0' 41 | implementation 'com.android.support:recyclerview-v7:28.0.0' 42 | implementation 'com.android.support:design:28.0.0' 43 | 44 | implementation project(':library') 45 | } -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/ChildAdapter.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library; 2 | 3 | import android.graphics.Color; 4 | import android.support.annotation.NonNull; 5 | import android.support.v4.view.PagerAdapter; 6 | import android.support.v4.view.ViewPager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.view.Gravity; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.TextView; 12 | import android.widget.Toast; 13 | 14 | /** 15 | * Created by yuyang on 2023/12/14. 16 | */ 17 | public class ChildAdapter extends RecyclerView.Adapter { 18 | 19 | private static final int TYPE_VIEWPAGER = 0; 20 | private static final int TYPE_TEXTVIEW = 1; 21 | private static final int VIEWPAGER_ITEM_COUNT = 5; 22 | 23 | private final int[] colors = new int[]{ 24 | Color.RED, 25 | Color.BLUE, 26 | Color.GREEN, 27 | Color.YELLOW, 28 | Color.CYAN, 29 | }; 30 | 31 | private String title; 32 | 33 | public ChildAdapter(String title) { 34 | this.title = title; 35 | } 36 | 37 | @Override 38 | public int getItemViewType(int position) { 39 | if (position == 0) { 40 | return TYPE_VIEWPAGER; 41 | } else { 42 | return TYPE_TEXTVIEW; 43 | } 44 | } 45 | 46 | @NonNull 47 | @Override 48 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { 49 | if (viewType == TYPE_VIEWPAGER) { 50 | ViewPager viewPager = new ViewPager(viewGroup.getContext()); 51 | viewPager.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 600)); 52 | return new RecyclerView.ViewHolder(viewPager) { 53 | }; 54 | } else { 55 | TextView textView = new TextView(viewGroup.getContext()); 56 | textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 57 | textView.setPadding(100, 100, 100, 100); 58 | textView.setGravity(Gravity.CENTER_VERTICAL); 59 | textView.setBackgroundColor(Color.WHITE); 60 | return new RecyclerView.ViewHolder(textView) { 61 | }; 62 | } 63 | } 64 | 65 | @Override 66 | public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { 67 | if (position == 0) { 68 | ((ViewPager) viewHolder.itemView).setAdapter(new PagerAdapter() { 69 | @Override 70 | public int getCount() { 71 | return VIEWPAGER_ITEM_COUNT; 72 | } 73 | 74 | @Override 75 | public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { 76 | return view == object; 77 | } 78 | 79 | @NonNull 80 | @Override 81 | public Object instantiateItem(@NonNull ViewGroup container, int position) { 82 | TextView textView = new TextView(container.getContext()); 83 | textView.setGravity(Gravity.CENTER); 84 | textView.setText(String.format("我是ViewPager的第%d个item", position)); 85 | textView.setBackgroundColor(colors[position]); 86 | 87 | container.addView(textView); 88 | return textView; 89 | } 90 | 91 | @Override 92 | public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { 93 | container.removeView((View) object); 94 | } 95 | }); 96 | } else { 97 | ((TextView) viewHolder.itemView).setText(title + " item " + position); 98 | ((TextView) viewHolder.itemView).setMinHeight((int) (200 + position * 1.1f)); 99 | viewHolder.itemView.setOnClickListener(new View.OnClickListener() { 100 | @Override 101 | public void onClick(View v) { 102 | Toast.makeText(v.getContext(), "click " + title + " item " + position, Toast.LENGTH_SHORT).show(); 103 | } 104 | }); 105 | } 106 | } 107 | 108 | @Override 109 | public int getItemCount() { 110 | return 100; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.support.v7.widget.LinearLayoutManager; 8 | import android.view.Menu; 9 | import android.view.MenuInflater; 10 | import android.view.MenuItem; 11 | 12 | import com.yuyang.library.nested.MainActivityWithoutTab; 13 | import com.yuyang.library.nestedrv.ParentRecyclerView; 14 | 15 | import java.util.Arrays; 16 | 17 | /** 18 | * 带Tab 19 | *

20 | * Created by yuyang on 2023/12/4. 21 | */ 22 | public class MainActivity extends AppCompatActivity { 23 | 24 | private ParentRecyclerView mParentRecyclerView; 25 | 26 | private ParentAdapter mParentAdapter; 27 | 28 | @Override 29 | protected void onCreate(@Nullable Bundle savedInstanceState) { 30 | super.onCreate(savedInstanceState); 31 | 32 | setContentView(R.layout.activity_main); 33 | 34 | mParentRecyclerView = findViewById(R.id.parent); 35 | mParentRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 36 | mParentRecyclerView.setAdapter(mParentAdapter = new ParentAdapter()); 37 | 38 | mParentAdapter.setDataList(Arrays.asList(R.mipmap.p1, R.mipmap.p2, R.mipmap.p3)); 39 | } 40 | 41 | @Override 42 | public boolean onCreateOptionsMenu(Menu menu) { 43 | MenuInflater inflater = getMenuInflater(); 44 | inflater.inflate(R.menu.menu_main, menu); 45 | return true; 46 | } 47 | 48 | @Override 49 | public boolean onOptionsItemSelected(MenuItem item) { 50 | if (item.getItemId() == R.id.action_tab) { 51 | Intent intent = new Intent(this, MainActivityWithoutTab.class); 52 | startActivity(intent); 53 | return true; 54 | } 55 | return super.onOptionsItemSelected(item); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/ParentAdapter.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library; 2 | 3 | import android.graphics.drawable.Drawable; 4 | import android.support.annotation.NonNull; 5 | import android.support.v4.content.ContextCompat; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.ImageView; 11 | import android.widget.Toast; 12 | 13 | import com.yuyang.library.nestedrv.ChildRecyclerView; 14 | import com.yuyang.library.nestedrv.INestedParentAdapter; 15 | 16 | import java.util.ArrayList; 17 | import java.util.Arrays; 18 | import java.util.List; 19 | 20 | /** 21 | * Created by yuyang on 2023/12/4. 22 | */ 23 | public class ParentAdapter extends RecyclerView.Adapter implements INestedParentAdapter { 24 | 25 | private static final int TYPE_ITEM = 0; 26 | 27 | private static final int TYPE_INNER = 1; 28 | 29 | private List dataList = new ArrayList<>(); 30 | 31 | private List tabs = Arrays.asList("推荐", "热点", "视频", "直播", "社会", "娱乐", "科技", "汽车", "体育", "财经", "军事", "国际", "时尚", "游戏", "旅游", "历史", "探索", "美食", "育儿", "养生", "故事", "美文"); 32 | 33 | private TabViewHolder mTabViewHolder; 34 | 35 | @NonNull 36 | @Override 37 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { 38 | if (viewType == TYPE_ITEM) { 39 | ImageView imageView = new ImageView(viewGroup.getContext()); 40 | imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 41 | return new RecyclerView.ViewHolder(imageView) { 42 | }; 43 | } 44 | return new TabViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_inner, viewGroup, false)); 45 | } 46 | 47 | @Override 48 | public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { 49 | int viewType = getItemViewType(position); 50 | if (viewType == TYPE_ITEM) { 51 | ImageView imageView = (ImageView) viewHolder.itemView; 52 | Drawable drawable = ContextCompat.getDrawable(viewHolder.itemView.getContext(), dataList.get(viewHolder.getAdapterPosition())); 53 | int width = drawable.getIntrinsicWidth(); 54 | int height = drawable.getIntrinsicHeight(); 55 | int targetHeight = viewHolder.itemView.getContext().getResources().getDisplayMetrics().widthPixels * height / width; 56 | ViewGroup.LayoutParams layoutParams = viewHolder.itemView.getLayoutParams(); 57 | layoutParams.height = targetHeight; 58 | imageView.setImageDrawable(drawable); 59 | imageView.setOnClickListener(new View.OnClickListener() { 60 | @Override 61 | public void onClick(View v) { 62 | Toast.makeText(v.getContext(), "点击了第" + viewHolder.getAdapterPosition() + "个", Toast.LENGTH_SHORT).show(); 63 | } 64 | }); 65 | } else { 66 | mTabViewHolder = (TabViewHolder) viewHolder; 67 | mTabViewHolder.bindData(tabs); 68 | } 69 | } 70 | 71 | @Override 72 | public int getItemCount() { 73 | return dataList.size() + 1; 74 | } 75 | 76 | @Override 77 | public int getItemViewType(int position) { 78 | return position < dataList.size() ? TYPE_ITEM : TYPE_INNER; 79 | } 80 | 81 | @Override 82 | public ChildRecyclerView getCurrentChildRecyclerView() { 83 | return mTabViewHolder == null ? null : mTabViewHolder.getCurrentChildRecyclerView(); 84 | } 85 | 86 | public void setDataList(List dataList) { 87 | this.dataList.clear(); 88 | if (dataList != null) { 89 | this.dataList.addAll(dataList); 90 | } 91 | notifyDataSetChanged(); 92 | } 93 | 94 | 95 | } 96 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/TabViewHolder.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library; 2 | 3 | import android.graphics.Rect; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.support.design.widget.TabLayout; 7 | import android.support.v4.view.PagerAdapter; 8 | import android.support.v4.view.ViewPager; 9 | import android.support.v7.widget.RecyclerView; 10 | import android.support.v7.widget.StaggeredGridLayoutManager; 11 | import android.view.View; 12 | import android.view.ViewGroup; 13 | 14 | import com.yuyang.library.nestedrv.ChildRecyclerView; 15 | 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | /** 20 | * Created by yuyang on 2023/12/4. 21 | */ 22 | public class TabViewHolder extends RecyclerView.ViewHolder { 23 | 24 | private final TabLayout mTabLayout; 25 | private final ViewPager mViewPager; 26 | 27 | private final List mViewList = new ArrayList<>(); 28 | 29 | private ChildRecyclerView mCurrentChildRecyclerView; 30 | 31 | public TabViewHolder(@NonNull android.view.View itemView) { 32 | super(itemView); 33 | 34 | mTabLayout = itemView.findViewById(R.id.tab_layout); 35 | mViewPager = itemView.findViewById(R.id.view_pager); 36 | 37 | mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { 38 | @Override 39 | public void onPageScrolled(int i, float v, int i1) { 40 | 41 | } 42 | 43 | @Override 44 | public void onPageSelected(int i) { 45 | if (!mViewList.isEmpty()) { 46 | mCurrentChildRecyclerView = mViewList.get(i); 47 | } 48 | } 49 | 50 | @Override 51 | public void onPageScrollStateChanged(int i) { 52 | 53 | } 54 | }); 55 | } 56 | 57 | public void bindData(List tabs) { 58 | mViewList.clear(); 59 | 60 | for (String str : tabs) { 61 | ChildRecyclerView childRecyclerView = new ChildRecyclerView(mViewPager.getContext()); 62 | childRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); 63 | childRecyclerView.setAdapter(new ChildAdapter(str)); 64 | childRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { 65 | @Override 66 | public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { 67 | super.getItemOffsets(outRect, view, parent, state); 68 | outRect.left = outRect.right = outRect.bottom = outRect.top = 10; 69 | } 70 | }); 71 | mViewList.add(childRecyclerView); 72 | } 73 | 74 | mCurrentChildRecyclerView = mViewList.get(mViewPager.getCurrentItem()); 75 | int lastItem = mViewPager.getCurrentItem(); 76 | mViewPager.setAdapter(new PagerAdapter() { 77 | 78 | @NonNull 79 | @Override 80 | public Object instantiateItem(@NonNull ViewGroup container, int position) { 81 | ChildRecyclerView childRecyclerView = mViewList.get(position); 82 | if (container == childRecyclerView.getParent()) { 83 | container.removeView(childRecyclerView); 84 | } 85 | container.addView(childRecyclerView); 86 | return childRecyclerView; 87 | } 88 | 89 | @Override 90 | public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { 91 | // super.destroyItem(container, position, object); 92 | container.removeView((View) object); 93 | } 94 | 95 | @Nullable 96 | @Override 97 | public CharSequence getPageTitle(int position) { 98 | return tabs.get(position); 99 | } 100 | 101 | @Override 102 | public int getCount() { 103 | return tabs.size(); 104 | } 105 | 106 | @Override 107 | public boolean isViewFromObject(@NonNull View view, @NonNull Object o) { 108 | return view == o; 109 | } 110 | }); 111 | mTabLayout.setupWithViewPager(mViewPager); 112 | mViewPager.setCurrentItem(lastItem); 113 | } 114 | 115 | public ChildRecyclerView getCurrentChildRecyclerView() { 116 | return mCurrentChildRecyclerView; 117 | } 118 | } -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/nested/MainActivityWithoutTab.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nested; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | 8 | import com.yuyang.library.R; 9 | import com.yuyang.library.nestedrv.ParentRecyclerView; 10 | 11 | import java.util.Arrays; 12 | 13 | /** 14 | * 不带Tab 15 | *

16 | * Created by yuyang on 2023/12/4. 17 | */ 18 | public class MainActivityWithoutTab extends AppCompatActivity { 19 | 20 | private ParentRecyclerView mParentRecyclerView; 21 | 22 | private ParentAdapterWithoutTab mParentAdapterWithoutTab; 23 | 24 | @Override 25 | protected void onCreate(@Nullable Bundle savedInstanceState) { 26 | super.onCreate(savedInstanceState); 27 | 28 | setContentView(R.layout.activity_main); 29 | 30 | mParentRecyclerView = findViewById(R.id.parent); 31 | mParentRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 32 | mParentRecyclerView.setAdapter(mParentAdapterWithoutTab = new ParentAdapterWithoutTab()); 33 | 34 | mParentAdapterWithoutTab.setDataList(Arrays.asList(R.mipmap.p1, R.mipmap.p2, R.mipmap.p3)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/java/com/yuyang/library/nested/ParentAdapterWithoutTab.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nested; 2 | 3 | import android.graphics.Rect; 4 | import android.graphics.drawable.Drawable; 5 | import android.support.annotation.NonNull; 6 | import android.support.v4.content.ContextCompat; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.support.v7.widget.StaggeredGridLayoutManager; 9 | import android.view.View; 10 | import android.view.ViewGroup; 11 | import android.widget.ImageView; 12 | import android.widget.Toast; 13 | 14 | import com.yuyang.library.ChildAdapter; 15 | import com.yuyang.library.nestedrv.ChildRecyclerView; 16 | import com.yuyang.library.nestedrv.INestedParentAdapter; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | /** 22 | * Created by yuyang on 2023/12/4. 23 | */ 24 | public class ParentAdapterWithoutTab extends RecyclerView.Adapter implements INestedParentAdapter { 25 | 26 | private static final int TYPE_ITEM = 0; 27 | 28 | private static final int TYPE_INNER = 1; 29 | 30 | private List dataList = new ArrayList<>(); 31 | 32 | private ChildRecyclerView childRecyclerView; 33 | 34 | @NonNull 35 | @Override 36 | public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { 37 | if (viewType == TYPE_ITEM) { 38 | ImageView imageView = new ImageView(viewGroup.getContext()); 39 | imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 40 | return new RecyclerView.ViewHolder(imageView) { 41 | }; 42 | } 43 | 44 | if (childRecyclerView == null) { 45 | childRecyclerView = new ChildRecyclerView(viewGroup.getContext()); 46 | childRecyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 47 | } else { 48 | if (childRecyclerView.getParent() != null) { 49 | ((ViewGroup) childRecyclerView.getParent()).removeView(childRecyclerView); 50 | } 51 | } 52 | return new RecyclerView.ViewHolder(childRecyclerView) { 53 | }; 54 | } 55 | 56 | @Override 57 | public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) { 58 | int viewType = getItemViewType(position); 59 | if (viewType == TYPE_ITEM) { 60 | ImageView imageView = (ImageView) viewHolder.itemView; 61 | Drawable drawable = ContextCompat.getDrawable(viewHolder.itemView.getContext(), dataList.get(viewHolder.getAdapterPosition())); 62 | int width = drawable.getIntrinsicWidth(); 63 | int height = drawable.getIntrinsicHeight(); 64 | int targetHeight = viewHolder.itemView.getContext().getResources().getDisplayMetrics().widthPixels * height / width; 65 | ViewGroup.LayoutParams layoutParams = viewHolder.itemView.getLayoutParams(); 66 | layoutParams.height = targetHeight; 67 | imageView.setImageDrawable(drawable); 68 | imageView.setOnClickListener(new View.OnClickListener() { 69 | @Override 70 | public void onClick(View v) { 71 | Toast.makeText(v.getContext(), "点击了第" + viewHolder.getAdapterPosition() + "个", Toast.LENGTH_SHORT).show(); 72 | } 73 | }); 74 | } else { 75 | childRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)); 76 | childRecyclerView.setAdapter(new ChildAdapter("默认")); 77 | childRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { 78 | @Override 79 | public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { 80 | super.getItemOffsets(outRect, view, parent, state); 81 | outRect.left = outRect.right = outRect.bottom = outRect.top = 10; 82 | } 83 | }); 84 | } 85 | } 86 | 87 | @Override 88 | public int getItemCount() { 89 | return dataList.size() + 1; 90 | } 91 | 92 | @Override 93 | public int getItemViewType(int position) { 94 | return position < dataList.size() ? TYPE_ITEM : TYPE_INNER; 95 | } 96 | 97 | @Override 98 | public ChildRecyclerView getCurrentChildRecyclerView() { 99 | return childRecyclerView; 100 | } 101 | 102 | public void setDataList(List dataList) { 103 | this.dataList.clear(); 104 | if (dataList != null) { 105 | this.dataList.addAll(dataList); 106 | } 107 | notifyDataSetChanged(); 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main_without_tab.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_inner.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 14 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 2 |

4 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/p1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/app/src/main/res/mipmap-xxxhdpi/p1.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/p2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/app/src/main/res/mipmap-xxxhdpi/p2.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/p3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/app/src/main/res/mipmap-xxxhdpi/p3.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FF6200EE 4 | #FF3700B3 5 | #D81B60 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NestedRecyclerView 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | plugins { 3 | id 'com.android.application' version '8.1.1' apply false 4 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=false -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 04 09:55:34 CST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | namespace 'com.yuyang.library.nestedrv' 7 | compileSdk 28 8 | 9 | defaultConfig { 10 | minSdk 23 11 | targetSdk 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | compileOptions { 25 | sourceCompatibility JavaVersion.VERSION_1_8 26 | targetCompatibility JavaVersion.VERSION_1_8 27 | } 28 | } 29 | 30 | dependencies { 31 | implementation 'com.android.support:appcompat-v7:28.0.0' 32 | implementation 'com.android.support:recyclerview-v7:28.0.0' 33 | implementation 'com.android.support:design:28.0.0' 34 | } -------------------------------------------------------------------------------- /library/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 -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /library/src/main/java/com/yuyang/library/nestedrv/ChildRecyclerView.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nestedrv; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.util.AttributeSet; 8 | import android.view.MotionEvent; 9 | import android.view.ViewParent; 10 | 11 | /** 12 | * 子RecyclerView 13 | *

14 | * Created by yuyang on 2023/12/4. 15 | */ 16 | public class ChildRecyclerView extends RecyclerView { 17 | 18 | private ParentRecyclerView mParentRecyclerView = null; 19 | 20 | /** 21 | * fling时的加速度 22 | */ 23 | private int mVelocity = 0; 24 | 25 | private int mLastInterceptX; 26 | 27 | private int mLastInterceptY; 28 | 29 | public ChildRecyclerView(@NonNull Context context) { 30 | this(context, null); 31 | } 32 | 33 | public ChildRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { 34 | this(context, attrs, 0); 35 | } 36 | 37 | public ChildRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { 38 | super(context, attrs, defStyle); 39 | init(); 40 | } 41 | 42 | private void init() { 43 | setOverScrollMode(OVER_SCROLL_NEVER); 44 | 45 | addOnScrollListener(new OnScrollListener() { 46 | @Override 47 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { 48 | super.onScrollStateChanged(recyclerView, newState); 49 | if (newState == SCROLL_STATE_IDLE) { 50 | dispatchParentFling(); 51 | } 52 | } 53 | }); 54 | } 55 | 56 | private void dispatchParentFling() { 57 | ensureParentRecyclerView(); 58 | // 子容器滚动到顶部,如果还有剩余加速度,就交给父容器处理 59 | if (mParentRecyclerView != null && isScrollToTop() && mVelocity != 0) { 60 | // 尽量让速度传递更加平滑 61 | float velocityY = NestedOverScroller.invokeCurrentVelocity(this); 62 | if (Math.abs(velocityY) <= 2.0E-5F) { 63 | velocityY = (float) this.mVelocity * 0.5F; 64 | } else { 65 | velocityY *= 0.65F; 66 | } 67 | mParentRecyclerView.fling(0, (int) velocityY); 68 | mVelocity = 0; 69 | } 70 | } 71 | 72 | @Override 73 | public boolean dispatchTouchEvent(MotionEvent ev) { 74 | if (ev.getAction() == MotionEvent.ACTION_DOWN) { 75 | mVelocity = 0; 76 | } 77 | 78 | int x = (int) ev.getRawX(); 79 | int y = (int) ev.getRawY(); 80 | if (ev.getAction() != MotionEvent.ACTION_MOVE) { 81 | mLastInterceptX = x; 82 | mLastInterceptY = y; 83 | } 84 | 85 | int deltaX = x - mLastInterceptX; 86 | int deltaY = y - mLastInterceptY; 87 | 88 | if (isScrollToTop() && Math.abs(deltaX) <= Math.abs(deltaY) && getParent() != null) { 89 | // 子容器滚动到顶部,继续向上滑动,此时父容器需要继续拦截事件。与父容器 onInterceptTouchEvent 对应 90 | getParent().requestDisallowInterceptTouchEvent(false); 91 | } 92 | return super.dispatchTouchEvent(ev); 93 | } 94 | 95 | @Override 96 | public boolean fling(int velocityX, int velocityY) { 97 | if (!isAttachedToWindow()) return false; 98 | boolean fling = super.fling(velocityX, velocityY); 99 | if (!fling || velocityY >= 0) { 100 | mVelocity = 0; 101 | } else { 102 | mVelocity = velocityY; 103 | } 104 | return fling; 105 | } 106 | 107 | public boolean isScrollToTop() { 108 | return !canScrollVertically(-1); 109 | } 110 | 111 | public boolean isScrollToBottom() { 112 | return !canScrollVertically(1); 113 | } 114 | 115 | private void ensureParentRecyclerView() { 116 | if (mParentRecyclerView == null) { 117 | ViewParent parentView = getParent(); 118 | while (!(parentView instanceof ParentRecyclerView)) { 119 | parentView = parentView.getParent(); 120 | } 121 | mParentRecyclerView = (ParentRecyclerView) parentView; 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /library/src/main/java/com/yuyang/library/nestedrv/INestedParentAdapter.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nestedrv; 2 | 3 | /** 4 | * ParentAdapter 需实现此接口 5 | *

6 | * Created by yuyang on 2023/12/4. 7 | */ 8 | public interface INestedParentAdapter { 9 | 10 | /** 11 | * 获取当前需要联动的子RecyclerView 12 | * 13 | * @return 14 | */ 15 | ChildRecyclerView getCurrentChildRecyclerView(); 16 | } 17 | -------------------------------------------------------------------------------- /library/src/main/java/com/yuyang/library/nestedrv/NestedOverScroller.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nestedrv; 2 | 3 | import android.support.annotation.NonNull; 4 | import android.support.v7.widget.RecyclerView; 5 | 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * 平滑滚动效果的辅助类 11 | *

12 | *

13 | * Created by yuyang on 2023/12/4. 14 | */ 15 | public class NestedOverScroller { 16 | 17 | public static float invokeCurrentVelocity(@NonNull RecyclerView rv) { 18 | try { 19 | Field viewFlinger = null; 20 | for (Class superClass = rv.getClass().getSuperclass(); superClass != null; superClass = superClass.getSuperclass()) { 21 | try { 22 | viewFlinger = superClass.getDeclaredField("mViewFlinger"); 23 | break; 24 | } catch (Throwable ignored) { 25 | } 26 | } 27 | 28 | if (viewFlinger == null) { 29 | return 0.0F; 30 | } else { 31 | viewFlinger.setAccessible(true); 32 | Object viewFlingerValue = viewFlinger.get(rv); 33 | Field scroller = viewFlingerValue.getClass().getDeclaredField("mScroller"); 34 | scroller.setAccessible(true); 35 | Object scrollerValue = scroller.get(viewFlingerValue); 36 | Field scrollerY = scrollerValue.getClass().getDeclaredField("mScrollerY"); 37 | scrollerY.setAccessible(true); 38 | Object scrollerYValue = scrollerY.get(scrollerValue); 39 | Field currVelocity = scrollerYValue.getClass().getDeclaredField("mCurrVelocity"); 40 | currVelocity.setAccessible(true); 41 | return (Float) currVelocity.get(scrollerYValue); 42 | } 43 | } catch (Throwable ignored) { 44 | return 0.0F; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /library/src/main/java/com/yuyang/library/nestedrv/ParentRecyclerView.java: -------------------------------------------------------------------------------- 1 | package com.yuyang.library.nestedrv; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.widget.RecyclerView; 7 | import android.util.AttributeSet; 8 | import android.view.MotionEvent; 9 | import android.view.VelocityTracker; 10 | import android.view.ViewConfiguration; 11 | 12 | /** 13 | * 父RecyclerView 14 | *

15 | * Created by yuyang on 2023/12/4. 16 | */ 17 | public class ParentRecyclerView extends RecyclerView { 18 | 19 | private final int mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); 20 | 21 | /** 22 | * fling时的加速度 23 | */ 24 | private int mVelocity = 0; 25 | 26 | private float mLastTouchY = 0f; 27 | 28 | private int mLastInterceptX; 29 | private int mLastInterceptY; 30 | 31 | /** 32 | * 用于向子容器传递 fling 速度 33 | */ 34 | private final VelocityTracker mVelocityTracker = VelocityTracker.obtain(); 35 | private int mMaximumFlingVelocity; 36 | private int mMinimumFlingVelocity; 37 | 38 | /** 39 | * 子容器是否消耗了滑动事件 40 | */ 41 | private boolean childConsumeTouch = false; 42 | /** 43 | * 子容器消耗的滑动距离 44 | */ 45 | private int childConsumeDistance = 0; 46 | 47 | public ParentRecyclerView(@NonNull Context context) { 48 | this(context, null); 49 | } 50 | 51 | public ParentRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { 52 | this(context, attrs, 0); 53 | } 54 | 55 | public ParentRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { 56 | super(context, attrs, defStyle); 57 | init(); 58 | } 59 | 60 | private void init() { 61 | ViewConfiguration configuration = ViewConfiguration.get(getContext()); 62 | mMaximumFlingVelocity = configuration.getScaledMaximumFlingVelocity(); 63 | mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); 64 | 65 | addOnScrollListener(new OnScrollListener() { 66 | @Override 67 | public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { 68 | super.onScrollStateChanged(recyclerView, newState); 69 | if (newState == SCROLL_STATE_IDLE) { 70 | dispatchChildFling(); 71 | } 72 | } 73 | }); 74 | } 75 | 76 | @Override 77 | public boolean dispatchTouchEvent(MotionEvent ev) { 78 | switch (ev.getAction()) { 79 | case MotionEvent.ACTION_DOWN: 80 | mVelocity = 0; 81 | mLastTouchY = ev.getRawY(); 82 | childConsumeTouch = false; 83 | childConsumeDistance = 0; 84 | 85 | ChildRecyclerView childRecyclerView = findNestedScrollingChildRecyclerView(); 86 | if (isScrollToBottom() && (childRecyclerView != null && !childRecyclerView.isScrollToTop())) { 87 | stopScroll(); 88 | } 89 | break; 90 | case MotionEvent.ACTION_UP: 91 | case MotionEvent.ACTION_CANCEL: 92 | childConsumeTouch = false; 93 | childConsumeDistance = 0; 94 | break; 95 | default: 96 | break; 97 | } 98 | 99 | try { 100 | return super.dispatchTouchEvent(ev); 101 | } catch (Exception e) { 102 | e.printStackTrace(); 103 | return false; 104 | } 105 | } 106 | 107 | @Override 108 | public boolean onInterceptTouchEvent(MotionEvent event) { 109 | if (isChildConsumeTouch(event)) { 110 | // 子容器如果消费了触摸事件,后续父容器就无法再拦截事件 111 | // 在必要的时候,子容器需调用 requestDisallowInterceptTouchEvent(false) 来允许父容器继续拦截事件 112 | return false; 113 | } 114 | // 子容器不消费触摸事件,父容器按正常流程处理 115 | return super.onInterceptTouchEvent(event); 116 | } 117 | 118 | /** 119 | * 子容器是否消费触摸事件 120 | */ 121 | private boolean isChildConsumeTouch(MotionEvent event) { 122 | int x = (int) event.getRawX(); 123 | int y = (int) event.getRawY(); 124 | if (event.getAction() != MotionEvent.ACTION_MOVE) { 125 | mLastInterceptX = x; 126 | mLastInterceptY = y; 127 | return false; 128 | } 129 | int deltaX = x - mLastInterceptX; 130 | int deltaY = y - mLastInterceptY; 131 | if (Math.abs(deltaX) > Math.abs(deltaY) || Math.abs(deltaY) <= mTouchSlop) { 132 | return false; 133 | } 134 | 135 | return shouldChildScroll(deltaY); 136 | } 137 | 138 | /** 139 | * 子容器是否需要消费滚动事件 140 | */ 141 | private boolean shouldChildScroll(int deltaY) { 142 | ChildRecyclerView childRecyclerView = findNestedScrollingChildRecyclerView(); 143 | if (childRecyclerView == null) { 144 | return false; 145 | } 146 | if (isScrollToBottom()) { 147 | // 父容器已经滚动到底部 且 向下滑动 且 子容器还没滚动到底部 148 | return deltaY < 0 && !childRecyclerView.isScrollToBottom(); 149 | } else { 150 | // 父容器还没滚动到底部 且 向上滑动 且 子容器已经滚动到顶部 151 | return deltaY > 0 && !childRecyclerView.isScrollToTop(); 152 | } 153 | } 154 | 155 | @Override 156 | public boolean onTouchEvent(MotionEvent e) { 157 | if (isScrollToBottom()) { 158 | // 如果父容器已经滚动到底部,且向上滑动,且子容器还没滚动到顶部,事件传递给子容器 159 | ChildRecyclerView childRecyclerView = findNestedScrollingChildRecyclerView(); 160 | if (childRecyclerView != null) { 161 | int deltaY = (int) (mLastTouchY - e.getRawY()); 162 | if (deltaY >= 0 || !childRecyclerView.isScrollToTop()) { 163 | mVelocityTracker.addMovement(e); 164 | if (e.getAction() == MotionEvent.ACTION_UP) { 165 | // 传递剩余 fling 速度 166 | mVelocityTracker.computeCurrentVelocity(1000, mMaximumFlingVelocity); 167 | float velocityY = mVelocityTracker.getYVelocity(); 168 | if (Math.abs(velocityY) > mMinimumFlingVelocity) { 169 | childRecyclerView.fling(0, -(int) velocityY); 170 | } 171 | mVelocityTracker.clear(); 172 | } else { 173 | // 传递滑动事件 174 | childRecyclerView.scrollBy(0, deltaY); 175 | } 176 | 177 | childConsumeDistance += deltaY; 178 | mLastTouchY = e.getRawY(); 179 | childConsumeTouch = true; 180 | return true; 181 | } 182 | } 183 | } 184 | 185 | mLastTouchY = e.getRawY(); 186 | 187 | if (childConsumeTouch) { 188 | // 在同一个事件序列中,子容器消耗了部分滑动距离,需要扣除掉 189 | MotionEvent adjustedEvent = MotionEvent.obtain( 190 | e.getDownTime(), 191 | e.getEventTime(), 192 | e.getAction(), 193 | e.getX(), 194 | e.getY() + childConsumeDistance, // 更新Y坐标 195 | e.getMetaState() 196 | ); 197 | 198 | boolean handled = super.onTouchEvent(adjustedEvent); 199 | adjustedEvent.recycle(); 200 | return handled; 201 | } 202 | 203 | if (e.getAction() == MotionEvent.ACTION_UP || e.getAction() == MotionEvent.ACTION_CANCEL) { 204 | mVelocityTracker.clear(); 205 | } 206 | 207 | try { 208 | return super.onTouchEvent(e); 209 | } catch (Exception ex) { 210 | ex.printStackTrace(); 211 | return false; 212 | } 213 | } 214 | 215 | @Override 216 | public boolean fling(int velX, int velY) { 217 | boolean fling = super.fling(velX, velY); 218 | if (!fling || velY <= 0) { 219 | mVelocity = 0; 220 | } else { 221 | mVelocity = velY; 222 | } 223 | return fling; 224 | } 225 | 226 | private void dispatchChildFling() { 227 | // 父容器滚动到底部后,如果还有剩余加速度,传递给子容器 228 | if (isScrollToBottom() && mVelocity != 0) { 229 | // 尽量让速度传递更加平滑 230 | float mVelocity = NestedOverScroller.invokeCurrentVelocity(this); 231 | if (Math.abs(mVelocity) <= 2.0E-5F) { 232 | mVelocity = (float) this.mVelocity * 0.5F; 233 | } else { 234 | mVelocity *= 0.46F; 235 | } 236 | ChildRecyclerView childRecyclerView = findNestedScrollingChildRecyclerView(); 237 | if (childRecyclerView != null) { 238 | childRecyclerView.fling(0, (int) mVelocity); 239 | } 240 | } 241 | mVelocity = 0; 242 | } 243 | 244 | public ChildRecyclerView findNestedScrollingChildRecyclerView() { 245 | if (getAdapter() instanceof INestedParentAdapter) { 246 | return ((INestedParentAdapter) getAdapter()).getCurrentChildRecyclerView(); 247 | } 248 | return null; 249 | } 250 | 251 | public boolean isScrollToBottom() { 252 | return !canScrollVertically(1); 253 | } 254 | 255 | public boolean isScrollToTop() { 256 | return !canScrollVertically(-1); 257 | } 258 | 259 | @Override 260 | public void scrollToPosition(final int position) { 261 | checkChildNeedScrollToTop(position); 262 | 263 | super.scrollToPosition(position); 264 | } 265 | 266 | @Override 267 | public void smoothScrollToPosition(int position) { 268 | checkChildNeedScrollToTop(position); 269 | 270 | super.smoothScrollToPosition(position); 271 | } 272 | 273 | private void checkChildNeedScrollToTop(int position) { 274 | if (position == 0) { 275 | // 父容器滚动到顶部,从交互上来说子容器也需要滚动到顶部 276 | ChildRecyclerView childRecyclerView = findNestedScrollingChildRecyclerView(); 277 | if (childRecyclerView != null) { 278 | childRecyclerView.scrollToPosition(0); 279 | } 280 | } 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /record.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/record.gif -------------------------------------------------------------------------------- /record.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/record.mp4 -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smuyyh/NestedRecyclerView/5354e1768032af9904f97d666a55ad5658c2840e/screenshot.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | gradlePluginPortal() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | 16 | rootProject.name = "NestedRecyclerView" 17 | 18 | include ':app' 19 | include ':library' 20 | --------------------------------------------------------------------------------