我在屏幕顶部有一个视图,我想要始终显示它(在每个设备中,即使键盘打开)。问题是在屏幕中间我有一个EditText。在某些设备中,如果EditText获得焦点,键盘会打开并使布局向上移动。我不想使用AdjustResize,因为它会导致背景图像拉伸。是否可以知道布局是否因为键盘打开而移动?另外,这种向上移动是如何计算的?我正在考虑在需要的时候重新定位视图
-First尝试解决这个问题:我已经尝试过协调器布局。我没有找到一个行为来做我想做的事情,所以我尝试实现我自己的行为。我在布局的底部添加了一个空间视图,每当这个视图改变其位置时,我都会尝试向下平移顶部视图。但是,即使layoutDependsOn()返回true,也不会调用onDependentViewChanged()来计算转换。
-Second试图解决这个问题:我在布局的底部再次添加了一个空间视图。此外,我还添加了一个onGlobalLayoutListener,以便跟踪键盘是否打开。如果是这样,我尝试计算空间视图的位置,并将其与之前的位置进行比较,以便向下移动顶视图。
-Third的尝试是使用AdjustNothing并自己动手翻译需要在键盘打开时重新定位自己的视图。这是唯一的一次尝试,给我带来了一些结果,但似乎有问题,在未来,我相信这将导致比它解决的问题更多的问题。
此外,我发现x,y,translationX,translationY在adjustPan中没有变化。计算正确位置的唯一方法是使用getLocationOnScreen()。但在视图布局之后,这是可能的。我们可以在布局视图之前计算它吗?
发布于 2019-04-05 23:09:02
为了便于将来参考,为了在AdjustPan模式下计算向上平移的像素,您必须执行类似以下代码的操作。基本上,在AdjustPan中,为了使聚焦的EditText完全可见,我们尽可能多地推送布局。
val rect = Rect()
constraintLayout.getWindowVisibleDisplayFrame(rect)
val editTextGlobalRect = Rect()
view.getGlobalVisibleRect(editTextGlobalRect)
//if it is true the editText will be hidden so the layout will be moved upwards due to adjust pan
val translation = if (editTextGlobalRect.bottom > visibleArea.bottom) {
//Calculate how much the layout is going to be pushed
editTextGlobalRect.bottom - visibleArea.bottom.toFloat()
} else {
0f
}此外,如果您想要计算视图的新位置,以便停留在相同的屏幕位置,您必须这样做:
val stationaryViewGlobalRect = Rect()
stationaryView.getGlobalVisibleRect(stationaryViewGlobalRect)
stationaryView.y = when {
translation <= stationaryViewGlobalRect.top -> {
//Stationary view is not hidden at all but it was moved upwards
stationaryViewGlobalRect.top - translation + resources.getDimension(R.dimen.stationary_view_margin_top)
}
translation <= stationaryViewGlobalRect.bottom -> {
//Stationary view is not fully hidden
translation + (stationaryViewGlobalRect.bottom - translation)
}
else -> translation + stationaryViewGlobalRect.top //Stationary view is fully hidden
}https://stackoverflow.com/questions/55451439
复制相似问题