Skip to content

Instantly share code, notes, and snippets.

@TomoyaShibata
Created July 9, 2016 05:43
Show Gist options
  • Save TomoyaShibata/5b05479e59892f0c3ce7979096ea4132 to your computer and use it in GitHub Desktop.
Save TomoyaShibata/5b05479e59892f0c3ce7979096ea4132 to your computer and use it in GitHub Desktop.
RecyclerView で区切り線引きたくなったら書くクラス
package Util
import android.R
import android.content.Context
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
/**
* RecyclerView に区切り線を提供します
*/
class DividerItemDecoration(context: Context, orientation: Int) : RecyclerView.ItemDecoration() {
private val attrs: IntArray by lazy { intArrayOf(R.attr.listDivider) }
private val mDivider: Drawable by lazy { context.obtainStyledAttributes(this.attrs).getDrawable(0) }
private var mOrientation: Int = 0
init {
val a = context.obtainStyledAttributes(this.attrs)
a.recycle()
setOrientation(orientation)
}
/**
* orientation の値を設定します
*/
fun setOrientation(orientation: Int) {
if (orientation != LinearLayoutManager.HORIZONTAL && orientation != LinearLayoutManager.VERTICAL) {
throw IllegalArgumentException("invalid orientation")
}
this.mOrientation = orientation
}
/**
* 区切り線の描画を行います
*/
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State): Unit
= if (this.mOrientation == LinearLayoutManager.VERTICAL) drawVertical(c, parent) else drawHorizontal(c, parent)
/**
* vertical 方向に区切り線を描画します
*/
fun drawVertical(c: Canvas, parent: RecyclerView): Unit {
val left = parent.paddingLeft
val right = parent.width - parent.paddingRight
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + this.mDivider.intrinsicHeight
this.mDivider.setBounds(left, top, right, bottom)
this.mDivider.draw(c)
}
}
/**
* horizontal 方向に区切り線を描画します
*/
fun drawHorizontal(c: Canvas, parent: RecyclerView) {
val top = parent.paddingTop
val bottom = parent.height - parent.paddingBottom
val childCount = parent.childCount
for (i in 0..childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val left = child.right + params.rightMargin
val right = left + this.mDivider.intrinsicHeight
this.mDivider.setBounds(left, top, right, bottom)
this.mDivider.draw(c)
}
}
/**
* 描画された水平線の上下左右のオフセットを設定します
*/
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State)
= if (this.mOrientation == LinearLayoutManager.VERTICAL) outRect.set(0, 0, 0, this.mDivider.intrinsicHeight) else outRect.set(0, 0, this.mDivider.intrinsicWidth, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment