【发布时间】:2020-08-27 22:46:26
【问题描述】:
我想在 EditText 旁边显示一个带有建议条目的框。 我想我必须设置 LayoutParams(就像 this question 中建议的那样。
但是,无论我尝试什么,框总是在左上角结束。
我尝试了什么: - 获取 LayoutParams 作为 MarginLayoutParams(它们是),并设置它们。将它们放回视图中以获得良好的测量效果。 - 上述链接中的所有答案
- 使用 TranslationX 和 -Y 更改位置(这可行,但会遇到其他问题,例如状态栏可能并不总是 24dp,而且似乎是 hack)
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(上面的 sn-p 在第 170 行,稍作编辑以显示我尝试过的事情)
我尝试过的其他事情:将 box 添加到不同的布局中,这在所有情况下都会导致在该布局的左上角绘制框
【问题讨论】:
-
父
ViewGroup是什么?EditText和 box 都是它的直接子代吗?您究竟想将框与EditText关联起来放在哪里? -
ConstraintLayout中的框是否存在?您是否以编程方式添加?如果是这样,您是否在尝试修改LayoutParams之前添加它?Views 默认没有任何LayoutParams,所以如果你在设置任何块之前运行第一个块,那将返回if,当你最终添加框时,它将获得默认的LayoutParams,将其放在左上角。 -
好的,我不经常使用
ConstraintLayout,但我猜边距被忽略了,因为盒子上没有限制。尝试将LayoutParams设置为ConstraintLayout.LayoutParams,并将其topToTop和startToStart字段设置为ConstraintLayout.LayoutParams.PARENT_ID。 -
另外,我之前忘了提,但是您是否考虑过为此使用
PopupWindow?这可能会更容易一些,即使在平台上,也经常这样做;例如,Spinner下拉菜单、上下文菜单等 -
yaaaaay 成功了!另外,我将研究我没有使用的
PopupWindow,因为我不知道它:)。另外:我不太清楚为什么我不只使用AutoCompleteTextView。非常感谢您的帮助!
标签: android kotlin android-view layoutparams