Ruidge 의 솔루션이 마음에 들었지만 XML의 제어력이 더 필요했습니다. 그래서 Kotlin으로 변경하고 속성을 추가했습니다.
1) 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) / res 디렉토리 에 attr 파일을 작성하고 이것을 추가하십시오
<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) 스타일 파일에 스타일 추가
<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) 이제 기본 스타일을 사용할 수 있습니다
<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
android:layout_width="match_parent"
android:layout_height="2dp"
/>
또는 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"/>