【发布时间】:2018-07-25 09:06:32
【问题描述】:
我想从另一个xml 文件中得到一个View 高度。这些我总是得到 0 作为高度:
fun getHeight(): Int {
val factory = LayoutInflater.from(context)
val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val customView = inflater.inflate(R.layout.custom_expandable_helper,null)
val relativeLayout = customView.findViewById<RelativeLayout>(R.id.container_height)
val textView = customView.findViewById<TextView>(R.id.tv_height)
textView.text = complaintText
val rlp = RelativeLayout(activity)
rlp.addView(customView)
activity?.window?.decorView!!.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener{
override fun onGlobalLayout() {
val obs = relativeLayout.viewTreeObserver
viewHeight = relativeLayout.height
obs.removeOnGlobalLayoutListener(this)
}
})
val hei = rlp.height
relativeLayout.post {
viewHeight = relativeLayout.height
}
return relativeLayout.height
}
在这段代码中,你可以看到很多镜头来获取高度,它们都是 0。
这就是我要膨胀的 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:id="@+id/container_height">
<TextView
android:id="@+id/tv_height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/et_sides"
android:text="sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample.sample."/>
【问题讨论】:
-
视图高度是整数还是长整数?
-
是整数