如何让父ConstraintLayout视图以编程方式匹配其子TextView高度

时间:2018-04-22 16:41:35

标签: android kotlin android-constraintlayout

学习ConstraintLayout和Kotlin真棒。我有一个constraintLayout popupView,它是TextView titleLabel的父视图。我想将popupView高度调整为其子titleLabel TextView的内容。 titleLabel高度因使用的文本字符串不同而有所不同。

对于高度布局参数,titleLabel和popupView都设置为WRAP_CONTENT,但是popupView没有被渲染。向popupView的constraintSet添加固定高度约束将呈现它,但当titleLabel高度更改时,固定高度将不起作用。

任何想法如何让它运作?这就是我所拥有的

{{1}}

2 个答案:

答案 0 :(得分:0)

您可以通过在连接函数

中切换视图#id的顺序来解决此问题
false

或者将ConstraintSet设置为popUpView。该字段已具有正确的名称^^

popupConstraintSet.connect(view.id, START, popupView.id, START, margin)
popupConstraintSet.connect(view.id, END, popupView.id, END, margin)
popupConstraintSet.centerHorizontally(view.id, popupView.id)
popupConstraintSet.centerVertically(view.id, popupView.id)

答案 1 :(得分:0)

这是我最终做的事情:

  • 删除popupView.layoutParams;高度的WRAP_CONTENT似乎被忽略了......
  • 使用WRAP_CONTENT将constrainHeight添加到constraintSet

onCreate现在是这样的:

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    view.id = 1
    popupView.id = 2
    titleLabel.id = 5

    popupView.addView(titleLabel)
    view.addView(popupView)

    titleLabel.layoutParams = ConstraintLayout.LayoutParams(
      ConstraintLayout.LayoutParams.MATCH_CONSTRAINT,
      ConstraintLayout.LayoutParams.WRAP_CONTENT)
    titleLabel.text = message


    var margin = 2 * Constants.SpacingStandard.toInt()
    val popupConstraintSet = ConstraintSet()

    popupConstraintSet.connect(popupView.id, START, view.id, START, margin)
    popupConstraintSet.connect(popupView.id, END, view.id, END, margin)
    popupConstraintSet.constrainHeight(popupView.id, ConstraintSet.WRAP_CONTENT)
    popupConstraintSet.centerHorizontally(popupView.id, view.id)
    popupConstraintSet.centerVertically(popupView.id, view.id)

    view.setConstraintSet(popupConstraintSet)

    setContentView(view)
  }
}