J'ai aimé la solution de Ruidge , mais j'avais besoin de plus de contrôle à partir de XML. Je l'ai donc changé en Kotlin et ajouté des attributs.
1) Copiez la classe Kotlin:
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)
companion object {
const val DIRECTION_VERTICAL = 0
const val DIRECTION_HORIZONTAL = 1
}
private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
val typedArray = context.obtainStyledAttributes(
attrs,
R.styleable.DashedDividerView,
defStyleAttr,
R.style.DashedDividerDefault
)
dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
direction =
typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)
paint.color = dColor
paint.style = Paint.Style.STROKE
paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
paint.strokeWidth = dWidth
typedArray.recycle()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
path.moveTo(0f, 0f)
if (direction == DIRECTION_HORIZONTAL) {
path.lineTo(measuredWidth.toFloat(), 0f)
} else {
path.lineTo(0f, measuredHeight.toFloat())
}
canvas.drawPath(path, paint)
}
}
2) Créez un fichier attr dans le répertoire / res et ajoutez-le
<declare-styleable name="DashedDividerView">
<attr name="dividerDashGap" format="dimension" />
<attr name="dividerDashWidth" format="dimension" />
<attr name="dividerDashColor" format="reference|color" />
<attr name="dividerDirection" format="enum">
<enum name="vertical" value="0" />
<enum name="horizontal" value="1" />
</attr>
</declare-styleable>
3) Ajoutez un style au fichier de styles
<style name="DashedDividerDefault">
<item name="dividerDashGap">2dp</item>
<item name="dividerDashWidth">2dp</item>
<!-- or any color -->
<item name="dividerDashColor">#EE0606</item>
<item name="dividerDirection">horizontal</item>
</style>
4) Vous pouvez maintenant utiliser le style par défaut
<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
/>
ou définir des attributs en XML
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
app:dividerDirection="horizontal"
app:dividerDashGap="2dp"
app:dividerDashWidth="2dp"
app:dividerDashColor="@color/light_gray"/>