伙计们!我有一个非常令人沮丧的问题。我有一个活动和一个自定义布局(RelativeLayout的子类)。此布局包含一个子RelativeLayout。子项的宽度是父项宽度的一半。孩子的身高是父母身高的一半。也有一个按钮。当我单击此按钮时,我将父布局的高度设置为1000px。在父级布局中,我覆盖了onSizeChanged方法,在该方法中,我将子视图的高度更改为父级的一半。但这不是第一次!仅当我第二次单击按钮时,我的更改才会应用。请问你能帮帮我吗?这是我的代码:
class TempLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : RelativeLayout(context, attrs, defStyle) {
lateinit var child: RelativeLayout
init {
setBackgroundColor(Color.BLUE)
post {
child = RelativeLayout(context)
child.layoutParams = LayoutParams(width / 2, height / 2).apply {
addRule(CENTER_IN_PARENT)
}
child.setBackgroundColor(Color.RED)
addView(child)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
if (oldh == 0 && oldw == 0) {
return
}
child.layoutParams.width = width / 2
child.layoutParams.height = height / 2
child.invalidate()
child.requestLayout()
invalidate()
requestLayout()
}
}
class TempActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_temp)
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val layout = findViewById<TempLayout>(R.id.tempLayout)
layout.layoutParams.height = 1000
layout.invalidate()
layout.requestLayout()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.TempActivity">
<TempLayout
android:id="@+id/tempLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintTop_toTopOf="parent">
</TempLayout>
<Button
android:id="@+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>