这次采用一个Activity管理多个拥有RecyclerView的Fragment页面,定制RecyclerView的ItemDecoration
本文分两个部分,第一部分为线性布局,第二部分为网格布局
一:LinearLayoutManager下的Vertical 与 Horizontal
完成功能总共分三个部分:
1.自定义一个简单的ItemDecoration
2.fragment中recycler部分的设置及关联
3.MainActivity中对于fragment的调用及管理
开始第一部分的正文:
1.定义一个简单的ItemDecoration,目的是通过改变drawable的样式,更改线条的style
如果想要自定义样式,只需要更改一下样式的数组即可
定义一个Direction_line的类继承自RecyclerView的ItemDecoration
package com.hjk.shiny.recycle_second;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import org.w3c.dom.Attr;
/**
* Created by HJK on 2017/8/3.
* 定义RecyclerView 分割线ItemDecoration
*/
public class Direction_line extends RecyclerView.ItemDecoration{
//定制的样式数组
public static final int []ATTRS={
android.R.attr.listDivider
};
//视图
public Drawable mDrawable;
//布局方向
public static final int HORIZONTAL= LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL=LinearLayoutManager.VERTICAL;
//设定的分割线方向--当作参数传入控制分割线的显示方向以配合布局的方向
public int mOrientation ;
/**
* constructor
* context--上下文
* director--分割线方向--
*/
public Direction_line (Context context , int director){
//TypeArray用来存储自定义的属性
final TypedArray typedArray=context.obtainStyledAttributes(ATTRS);
//获取自定义视图
mDrawable=typedArray.getDrawable(0);
//获取视图后回收TpyeArray
typedArray.recycle();
//设置画线方向
setOrientation(director);
}
private void setOrientation(int orientation){
if(orientation!=HORIZONTAL&&orientation!=VERTICAL){
throw new IllegalArgumentException();
}
//赋值指定的方向
mOrientation=orientation;
}
/**
* 画图
* canvas 画布
* recyclerView
* state
*/
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
super.onDraw(c, parent, state);
//不同的布局方向指定不同的绘画方法
if (mOrientation == VERTICAL) {
//垂直
drawVertical(c,parent);
} else {
//水平
drawHorizontal(c,parent);
}
}
//画布上绘画
public void drawHorizontal(Canvas c,RecyclerView view){
final int top=view.getTop();
final int bottom=view.getHeight()-view.getPaddingBottom();
int count=view.getChildCount();
for(int i=0;i<count;i++){
View child=view.getChildAt(i);
RecyclerView.LayoutParams params=(RecyclerView.LayoutParams)child.getLayoutParams();
int left=child.getLeft();
int right=left+mDrawable.getIntrinsicWidth();
//设置边界