为什么我的 LayoutParams 不会改变我的布局? [英] Why won't my LayoutParams change my layout?
问题描述
我想在 EditText 旁边显示一个带有建议条目的框.我想我必须设置 LayoutParams(就像 这个问题.
I want to display a box with suggested entries next to an EditText. I figured I'd have to set LayoutParams (like suggested in this question.
然而,无论我尝试什么,框总是在左上角结束.
However, no matter what I try, the box always ends up in the top left corner.
我尝试过的:- 获取 LayoutParams 作为 MarginLayoutParams(它们是),并设置它们.将它们放回视图中以进行良好测量.- 上面提到的链接中的所有答案
What I tried: - get LayoutParams as MarginLayoutParams (which they are), and set them. Set them back in the view for good measure. - All the answers in the link mentioned above
- 使用 TranslationX 和 -Y 更改位置(有效,但会遇到其他问题,例如状态栏可能不总是 24dp 并且似乎是一个黑客)
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如下:
the function View.Setmargins is as follows:
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()
}
}
我想做的事情的完整来源 这里(上面的片段在第 170 行,稍微编辑了一下以显示我尝试过的内容)
Complete source of the thing I want to do here (snippet above is at line 170, edited it a bit to show things I've tried)
我尝试过的其他事情:将 box
添加到不同的布局,这在所有情况下都会导致在该布局的左上角绘制框
Other things I have tried: add box
to different layouts, which in all cases results in the box being drawn in the top-left corner of that layout
推荐答案
对于任何和我有同样问题的人:Mike M. 建议将 LayoutParams
设为 ConstraintLayout.LayoutParams
,并设置其 topToTop
和 startToStart
ConstraintLayout.LayoutParams.PARENT_ID
的字段成功了,即.
For anybody having the same problem as I had:
Mike M. 's suggestion to get the LayoutParams
as ConstraintLayout.LayoutParams
, and also set its topToTop
and startToStart
fields to ConstraintLayout.LayoutParams.PARENT_ID
did the trick, ie.
(box?.layoutParams as ConstraintLayout.LayoutParams).apply{
topToTop = ConstraintLayout.LayoutParams.PARENT_ID
startToStart = ConstraintLayout.LayoutParams.PARENT_ID
topMargin = top
marginStart = left
}
这篇关于为什么我的 LayoutParams 不会改变我的布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!