需求
>
想实现一个仿网易新闻的页面,上面是轮播的图片,下面是 RecyclerView 显示新闻列表。
本文链接 http://blog.csdn.net/never_cxb/article/details/50520270,转载请注明出处。
错误方法
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout ...>
<ViewPager ... />
<android.support.v7.widget.RecyclerView .../>
</LinearLayout>
这样布局 ViewPager 在 RecyclerView 的上面,如果不做特殊处理,当下滑 RecyclerView 加载更多内容的时候,ViewPager会固定不动。
正确的效果是下滑加载更多的时候,ViewPager 会滑出页面,释放空间供其他内容展示。
解决思路
方法有两种
- ViewPager作为 RecyclerView 的第0项,也就是 Header(本文采用该方法)
- 利用ScrollView,重写一些方法解决滑动冲突
总xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/rcv_article_latest"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
很简单,一个RecyclerView就行了
头部 ViewPager 的viewholder_article_header.xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--ViewPager 热门文章图片展示-->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/gray_light">
<android.support.v4.view.ViewPager
android:id="@+id/vp_hottest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary" />
<LinearLayout
android:id="@+id/ll_hottest_indicator"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:orientation="horizontal" />
</FrameLayout>
</LinearLayout>
FrameLayout里面的ViewPager和LinearLayout是覆盖显示的,实现在图片的下方有个小圆点标记滑动到了第一张图片。
新闻项 viewholder_article_item.xml 布局
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:id="@+id/cv_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRa