Skip to content

Commit

Permalink
refactor: make sure CandidatesView positioning correct on first time …
Browse files Browse the repository at this point in the history
…showup
  • Loading branch information
WhiredPlanck committed Jan 27, 2025
1 parent c32c297 commit 0a5e944
Showing 1 changed file with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import android.annotation.SuppressLint
import android.graphics.RectF
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.view.ViewTreeObserver.OnPreDrawListener
import android.view.inputmethod.CursorAnchorInfo
import androidx.core.graphics.component1
import androidx.core.graphics.component2
Expand Down Expand Up @@ -57,6 +59,21 @@ class CandidatesView(
private val anchorPosition = RectF()
private val parentSize = floatArrayOf(0f, 0f)

private var shouldUpdatePosition = false

private val layoutListener =
OnGlobalLayoutListener {
shouldUpdatePosition = true
}

private val preDrawListener =
OnPreDrawListener {
if (shouldUpdatePosition) {
updatePosition()
}
true
}

private val preeditUi =
PreeditUi(ctx, theme).apply {
preedit.setOnCursorMoveListener { position ->
Expand Down Expand Up @@ -162,6 +179,7 @@ class CandidatesView(
}
translationX = x
translationY = y
shouldUpdatePosition = false
}

private val decorLocation = floatArrayOf(0f, 0f)
Expand All @@ -170,7 +188,6 @@ class CandidatesView(
info: CursorAnchorInfo,
updateLocation: (FloatArray, FloatArray) -> Unit,
) {
if (position != PopupPosition.FOLLOW) return
val bounds = info.getCharacterBounds(0)
// update anchorPosition
if (bounds == null) {
Expand Down Expand Up @@ -230,4 +247,16 @@ class CandidatesView(
isFocusable = false
layoutParams = ViewGroup.LayoutParams(wrapContent, wrapContent)
}

override fun onAttachedToWindow() {
super.onAttachedToWindow()
candidatesUi.root.viewTreeObserver.addOnGlobalLayoutListener(layoutListener)
viewTreeObserver.addOnPreDrawListener(preDrawListener)
}

override fun onDetachedFromWindow() {
viewTreeObserver.removeOnPreDrawListener(preDrawListener)
candidatesUi.root.viewTreeObserver.removeOnGlobalLayoutListener(layoutListener)
super.onDetachedFromWindow()
}
}

0 comments on commit 0a5e944

Please sign in to comment.