gpt4 book ai didi

android - onDraw 在自定义 View 中的 onMeasure 之前被调用

转载 作者:行者123 更新时间:2023-11-29 22:55:22 29 4
gpt4 key购买 nike

我在自定义 View 中有两个方法,onMeasure 和 onDraw。我有一个函数用于从源设置数据并使用使 View 函数无效来重绘 View 。我使用 onMeasure 来获取计算所需的 View 宽度。但是当我使用无效函数时,首先调用 onDraw,然后调用我的 onMeasure。因此我的 View 宽度始终为 0px。

我试过调用 requestLayout() 然后 invalidate() 重绘 View

override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)

val pointY = 15.px.toFloat()
var pointX = oneCellWidth.toFloat() / 2f

totalDays.forEach { day ->
val isWorkedDay = workedDays.filter { it.date == day.date }.size
if (isWorkedDay > 0) {
canvas?.drawCircle(pointX, pointY, 8f, circlePaint)
}
pointX += oneCellWidth
}
}

fun submitData(totalDays: List<Day>, workedDays: List<WorkedDateAndTime>, color: Int) {
this.totalDays = totalDays
this.workedDays = workedDays
circlePaint.color = color
oneCellWidth = viewWidth / totalDays.size
invalidate()
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)

val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)

if (widthMode == MeasureSpec.EXACTLY) {
viewWidth = widthSize

}
}

需要 viewWidth 不具有 View 宽度值。

最佳答案

我猜问题的发生是因为您在调用 View.invalidate() 之前阅读了 viewWidth。因此,当您读取 viewWidth 时,它仍然具有旧值。

因此,我建议进行以下更改:

override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)

oneCellWidth = viewWidth / totalDays.size // Add this
val pointY = 15.px.toFloat()
var pointX = oneCellWidth.toFloat() / 2f

totalDays.forEach { day ->
val isWorkedDay = workedDays.filter { it.date == day.date }.size
if (isWorkedDay > 0) {
canvas?.drawCircle(pointX, pointY, 8f, circlePaint)
}
pointX += oneCellWidth
}
}

fun submitData(totalDays: List<Day>, workedDays: List<WorkedDateAndTime>, color: Int) {
this.totalDays = totalDays
this.workedDays = workedDays
circlePaint.color = color
// oneCellWidth = viewWidth / totalDays.size --> Remove this
requestLayout() // Add this. invalidate only request re-draw. requestLayout will request to re-measure
invalidate()
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)

val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec)

if (widthMode == MeasureSpec.EXACTLY) {
viewWidth = widthSize
}
}

这样,您就可以避免在重新执行 onMeasure 之前读取 viewWidth 的问题。在这些更改之后,您在 onDraw 期间读取 viewWidth,它始终在 onMeasure 之后执行(如果您调用 requestLayout()当然。

关于android - onDraw 在自定义 View 中的 onMeasure 之前被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465387/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com