我遇到了类似的问题,我需要使用键盘平移编辑文本。我使用“AdjustUnspecified”作为我的窗口软输入模式,并执行以下操作以实现想要的行为。
1- 为方便起见,实现以下实用功能
fun Activity.getRootView(): View {
return findViewById<View>(android.R.id.content)
}
fun Context.convertDpToPx(dp: Float): Float {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
this.resources.displayMetrics
)
}
fun Activity.isKeyboardOpen(): Boolean {
val visibleBounds = Rect()
this.getRootView().getWindowVisibleDisplayFrame(visibleBounds)
val heightDiff = getRootView().height - visibleBounds.height()
val marginOfError = Math.round(this.convertDpToPx(50F))
return heightDiff > marginOfError
}
2- 在您的主要活动中,添加以下内容; (假设你的主activity的layout id是“main_activity_layout”)
在类的顶部声明一个监听器;
lateinit var listener: ViewTreeObserver.OnGlobalLayoutListener
然后,执行以下操作;
override fun onResume() {
super.onResume()
listener = object : ViewTreeObserver.OnGlobalLayoutListener {
// Keep a reference to the last state of the keyboard
private var lastState: Boolean = isKeyboardOpen()
/**
* Something in the layout has changed
* so check if the keyboard is open or closed
* and if the keyboard state has changed
* save the new state and invoke the callback
*/
override fun onGlobalLayout() {
val isOpen = isKeyboardOpen()
if (isOpen == lastState) {
return
} else {
onKeyboardStateChanged(isOpen)
lastState = isOpen
}
}
}
getRootView().viewTreeObserver?.addOnGlobalLayoutListener(listener)
}
private fun onKeyboardStateChanged(open: Boolean) {
runOnUiThread {
if (open) {
val screenHeight = resources.displayMetrics.heightPixels
TransitionManager.beginDelayedTransition(main_activity_layout as ViewGroup)
main_activity_layout.scrollTo(0, screenHeight / 4)
} else {
TransitionManager.beginDelayedTransition(main_activity_layout as ViewGroup)
main_activity_layout.scrollTo(0, 0)
}
}
}
override fun onPause() {
super.onPause()
getRootView().viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
您可以通过在此处修改滚动值来修改平移量
main_activity_layout.scrollTo(0, screenHeight / 4)