我想在EditText旁边显示一个带有建议条目的框。我认为我必须设置LayoutParams(如this question中建议的那样。
但是,无论我尝试什么,该框始终会出现在左上角。
我尝试过:-获得LayoutParams作为MarginLayoutParams(它们是),并进行设置。将它们重新放置在视图中以进行良好测量。-上述链接中的所有答案
val layoutParams = box?.layoutParams
//val layoutParams = ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply{
// setMargins(left, top, 0,0)
//}
if (layoutParams !is ViewGroup.MarginLayoutParams) return@onTextChanged
//layoutParams.leftMargin = left
layoutParams.marginStart = left
layoutParams.topMargin = top
box?.layoutParams = layoutParams // Don't think this is necessary
Log.d(TAG, "$layoutParams")
// works, but don't like it
// box?.translationX = left.toFloat()
// box?.translationY = top.toFloat()
//doesn't work
//box?.setMargins(left, top, right, 1000)
函数View.Setmargins如下:
fun View.setMargins(left: Int, top: Int, right: Int, bottom: Int) {
if (layoutParams is MarginLayoutParams) {
val p = layoutParams as MarginLayoutParams
p.setMargins(left, top, right, bottom)
requestLayout()
}
}
我想做的事情的完整源代码here(上面的片段在第170行,对其进行了一些编辑以显示我尝试过的事情)]
[我尝试过的其他事情:将box
添加到不同的布局,这在所有情况下都会导致在该布局的左上角绘制方框
对于与我有相同问题的任何人:Mike M.的建议是将LayoutParams
设为ConstraintLayout.LayoutParams
,并将其topToTop
和startToStart
字段设置为ConstraintLayout.LayoutParams.PARENT_ID
的建议就起作用了,即。
(box?.layoutParams as ConstraintLayout.LayoutParams).apply{
topToTop = ConstraintLayout.LayoutParams.PARENT_ID
startToStart = ConstraintLayout.LayoutParams.PARENT_ID
topMargin = top
marginStart = left
}