![](/img/trans.png)
[英]In Android how to get the width of the Textview which is set to Wrap_Content
[英]Kotlin how get width of wrap_content TextView
我有一個問題,因為我需要我的 TextView 的寬度。 我已經有了布局的寬度,但我也需要有特定元素的寬度。 在這種情況下 TextView。 我正在嘗試獲取它,但我認為 addOnLayoutChangeListener 正在另一個 scope 或某事上進行,因為當我嘗試將寬度分配給 var textWidth 我不能這樣做並且變量返回 0,但在 println 我可以看到有我需要的值。 我怎樣才能得到這個值?
var textWidth = 0
textViewOne.addOnLayoutChangeListener {
v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom
-> textWidth = right-left
println("${right-left}") <-- this return 389
}
println("${textWidth}") <-- this return 0
任何提示如何取 TextView 的寬度?
我相信在此階段不會評估視圖尺寸,因此您別無選擇,只能等到布局完全呈現。
假設您沒有測量單個視圖,我建議將OnGlobalLayoutListener
附加到根視圖:
rootView.viewTreeObserver.addOnGlobalLayoutListener {
// Do your thing
}
如果您希望代碼只執行一次:
rootView.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
rootView.viewTreeObserver.removeOnGlobalLayoutListener(this)
// Do your thing
}
})
如果有人需要解決方案,我剛剛解決了問題,這對我有用:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val displayMetrics: DisplayMetrics = applicationContext.resources.displayMetrics
val pxWidth = displayMetrics.widthPixels
val baseLayout = findViewById<LinearLayout>(R.id.baseLayout)
baseLayout.doOnLayout {
val textViewOne = findViewById<TextView>(R.id.textVieOne)
val oneWidth = textViewOne.width
val textViewTwo = findViewById<TextView>(R.id.textViewTwo)
val twoWidth = textViewTwo.width
val textViewThree = findViewById<TextView>(R.id.textViewThree)
val threeWidth = textViewThree.width
val sumOfChildWidths = oneWidth + twoWidth + threeWidth
if(pxWidth <= sumOfChildWidths){
textViewThree.isVisible = false
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.