【发布时间】:2020-08-23 08:13:57
【问题描述】:
这里我将根布局高度设置为 android:layout_height="400dp"。
<LinearLayout 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:id="@+id/container"
android:orientation="vertical"
android:layout_height="400dp"
tools:context=".FirstFragment">
<ImageButton
android:id="@+id/sleep_timer_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher_background"
android:gravity="center_vertical|center_horizontal"
android:padding="20dp"
android:scaleType="fitXY"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toBottomOf="@+id/guideline31"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="@+id/guideline24"
app:layout_constraintStart_toStartOf="@+id/guideline23"
app:layout_constraintTop_toTopOf="@+id/guideline30" />
<TextView
android:id="@+id/textview_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_first_fragment"
app:layout_constraintBottom_toTopOf="@id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textview_first" />
</LinearLayout>
我想以编程方式接收容器高度(400dp)。我尝试了所有方法
container.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
container.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.AT_MOST)
container.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY)
val height = measuredHeight
还有
val viewTreeObserver: ViewTreeObserver = container.viewTreeObserver
if (viewTreeObserver.isAlive) {
viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
container.viewTreeObserver.removeOnGlobalLayoutListener(this)
val viewHeight: Int = container.height
val viewHeight1: Int = container.measuredHeight
}
})
}
没有任何作用。如何以编程方式获取容器高度(400)?
【问题讨论】:
标签: android xml android-layout kotlin