Search code examples
androidkotlinwidth

Kotlin how get width of wrap_content TextView


I have a problem, because I need to have width of my TextView. I have already width of my Layout, but I need to have a width of specific element too. In this case TextView. I'm trying to get it, but I think that addOnLayoutChangeListener is going on another scope or sth because when I try to assign width to var textWidth I can't do this and variable return 0, but in println I can see that there is a value which I need. How can I get this value?

           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

Any tips how to do take width of TextView?


Solution

  • I just solved problem if anyone need solution this workes for me:

    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
            }
        }
    }