1.布局(用SwipeRefreshLayout实现下拉刷新)
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
2.RecyclerView的itemView布局
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp">
<ImageView
android:id="@+id/item_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="@mipmap/panda" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/item_img"
android:layout_margin="1dp"
android:background="#8c282828"
android:orientation="horizontal">
<TextView
android:id="@+id/item_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:text="大熊猫"
android:textColor="#ffffff"
android:textSize="15sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="国宝"
android:textColor="#de3636"
android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>
3.RecyclerView数据展示,见RecyclerView的简单使用
4.下拉刷新要借助SwipeRefreshLayout
// 下拉刷新(SwipeRefreshLayou设置刷新的监听)
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// 下拉刷新,清空数据源,重新获取最新数据
}
});
注意:刷新完毕要关闭刷新动画
// 数据已经更新,关闭刷新动画
// 如果不关闭会一直转圈
if (refreshLayout.isRefreshing()) {
refreshLayout.setRefreshing(false);
}
5.上拉加载需要添加OnScrollListener监听事件
// 上拉加载需要添加滚动监听事件
// 这里实现LinearLayoutManager并且是VERTAL方向的监听
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
// 满足条件 执行上拉加载数据
if (newState == RecyclerView.SCROLL_STATE_IDLE && isBottom) {
// 填充下一页数据...
// 注意:加载完 要置为false
isBottom = false;
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// dy>0 代表向下滚动
super.onScrolled(recyclerView, dx, dy);
int lastVisibleItemPosition = manager.findLastVisibleItemPosition();
int itemCount = manager.getItemCount();
// 如果最后一个可见的View的position 等于 itemCount-1 代表滚动到底部
isBottom = itemCount-1 == lastVisibleItemPosition && itemCount>0;
}
});