RecyclerView用法
1、添加依赖
在AS的中添加依赖,然后同步一下就可以引入依赖包:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile(':espresso-core:2.2.2', {
exclude group: '', module: 'support-annotations'
})
compile ':appcompat-v7:25.1.0'
compile ':recyclerview-v7:25.1.0'
testCompile 'junit:junit:4.12'
}
2、在xml布局文件中创建一个RecyclerView的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="/apk/res/android"
xmlns:tools="/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="">
<.
android:id="@+id/grid_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
RecyclerView自定义行列间距
1、设置宫格布局、瀑布流布局间距
/**
* 设置RecyclerView GridLayoutManager or StaggeredGridLayoutManager spacing
* Created by john on 17-1-5.
*/
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, state) {
int position = (view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
= spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
= (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
= spacing;
}
= spacing; // item bottom
} else {
= column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
= spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
= spacing; // item top
}
}
}
}
2、正确使用姿势
GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN, , false);
(layoutManager);
(new GridSpacingItemDecoration(COLUMN, getResources().getDimensionPixelSize(.padding_middle), true));
(true);
mRvGridAdapter = new RvGridAdapter(this);
(());
(mRvGridAdapter);
3、设置线性布局间距
/**
* 设置RecyclerView LinearLayoutManager spacing
* Created by john on 17-1-5.
*/
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, state) {
= space;
= space;
= space;
// Add top margin only for the first item to avoid double space between items
if ((view) == 0) {
= space;
} else {
= 0;
}
}
}