【问题标题】:Buttons in a RelativeLayout disappear after changing LayoutParams更改 LayoutParams 后,RelativeLayout 中的按钮消失
【发布时间】:2020-11-24 16:44:11
【问题描述】:

我在相对布局中有五个按钮,如果我尝试动态更改它们的高度,一些按钮会消失。

How buttons are looking before clicking

Buttons after clicking

val w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45f, resources.displayMetrics)
    btn_ran.setOnClickListener {
        btn_1.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_3.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_4.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_2.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)
        btn_5.layoutParams = RelativeLayout.LayoutParams(w.toInt(), 700)

    }

我想要做的就是在单击按钮时随机更改所有按钮的高度。

【问题讨论】:

  • 他们可能会离开屏幕视图。试着把它放在一个滚动视图中。

标签: android android-studio android-layout android-view android-button


【解决方案1】:

如果你只想把height改成随机值你可以这样:

button1.setOnClickListener {
    val h = (100..500).random() //random integer between 100 and 500
    button1.layoutParams.height = h
    button2.layoutParams.height = h
    button1.requestLayout() //refresh layout
}

【讨论】:

    【解决方案2】:

    我怀疑您在创建新的LayoutParams 对象时丢失了相对定位 属性。请记住,layout_toEndOf 之类的属性是布局参数的一部分。

    试试这个:

    val w = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45f, resources.displayMetrics)
    btn_ran.setOnClickListener {
        btn_1.updateLayoutParams { this.width = w }
        btn_3.updateLayoutParams { this.width = w }
        btn_4.updateLayoutParams { this.width = w }
        btn_2.updateLayoutParams { this.width = w }
        btn_5.updateLayoutParams { this.width = w }
    }
    

    这利用了核心 KTX 库中的 the updateLayoutParams extension function。它将保持LayoutParams 的所有内容相同,但还允许您修改宽度。

    如果您不能使用 Core KTX,那么您可以更冗长一些。将这些调用中的每一个替换为以下内容:

    val params1 = btn_1.layoutParams
    params1.width = w
    btn_1.layoutParams = params1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多