Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. import android.graphics.Canvas
  2. import android.graphics.drawable.Drawable
  3. import android.util.TypedValue
  4. import androidx.recyclerview.widget.LinearLayoutManager
  5. import androidx.recyclerview.widget.RecyclerView
  6.  
  7. /**
  8. * [RecyclerView] item decoration which adds horizontal divider between items.
  9. *
  10. * @author Muhammad Saeed
  11. */
  12. @Suppress("unused")
  13. class DividerItemDecoration(
  14. private val drawable: Drawable,
  15. private val marginLeft: Float = 16f,
  16. private val marginRight: Float = 16f,
  17. private val marginTop: Float = 16f,
  18. private val marginBottom: Float = 16f,
  19. private val dividerWidth: Int = 2
  20. ) : RecyclerView.ItemDecoration() {
  21.  
  22. override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
  23. super.onDrawOver(c, parent, state)
  24.  
  25. for (i in 0 until parent.childCount - 1) {
  26. val child = parent.getChildAt(i)
  27. val params = child.layoutParams as RecyclerView.LayoutParams
  28.  
  29. if (parent.layoutManager !is LinearLayoutManager) {
  30. return
  31. }
  32.  
  33. if ((parent.layoutManager as LinearLayoutManager).orientation == RecyclerView.VERTICAL) {
  34. val top = child.bottom - params.bottomMargin - dividerWidth
  35. val bottom = child.bottom - params.bottomMargin
  36.  
  37. val left = child.left - params.leftMargin + TypedValue.applyDimension(
  38. TypedValue.COMPLEX_UNIT_DIP,
  39. marginLeft,
  40. parent.context?.resources?.displayMetrics
  41. ).toInt()
  42.  
  43. val right = child.right - params.rightMargin - TypedValue.applyDimension(
  44. TypedValue.COMPLEX_UNIT_DIP,
  45. marginRight,
  46. parent.context?.resources?.displayMetrics
  47. ).toInt()
  48.  
  49. drawable.setBounds(left, top, right, bottom)
  50. drawable.draw(c)
  51. } else {
  52. val top = child.top - params.topMargin + TypedValue.applyDimension(
  53. TypedValue.COMPLEX_UNIT_DIP,
  54. marginTop,
  55. parent.context?.resources?.displayMetrics
  56. ).toInt()
  57. val bottom = child.bottom - params.bottomMargin - TypedValue.applyDimension(
  58. TypedValue.COMPLEX_UNIT_DIP,
  59. marginBottom,
  60. parent.context?.resources?.displayMetrics
  61. ).toInt()
  62.  
  63. val left = child.right - params.rightMargin - dividerWidth
  64. val right = child.right - params.rightMargin
  65.  
  66. drawable.setBounds(left, top, right, bottom)
  67. drawable.draw(c)
  68. }
  69. }
  70.  
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement