Ich mochte die Lösung von Ruidge , aber ich brauchte mehr Kontrolle über XML. Also habe ich es in Kotlin geändert und Attribute hinzugefügt.
1) Kopieren Sie die Kotlin-Klasse:
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) Erstellen Sie eine attr- Datei im Verzeichnis / res und fügen Sie diese hinzu
<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) In einen Stil der Stile - Datei
<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) Jetzt können Sie den Standardstil verwenden
<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
/>
oder Attribute in XML festlegen
<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"/>