re-setting a TextView height programmatically

后端 未结 6 1084
甜味超标
甜味超标 2020-12-24 11:20

I want to reset a textView height after I have added it to the main window in the xml file.

inside a RelativeLayout,

  

        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 12:07

    In Kotlin with DP to pixels translation

      changeTextHeight.setOnClickListener { view ->
    
             // random height for testing
            val randomHeightInDP = Random().nextFloat() * (50.0f - 10.0f) + 10
    
            // set Height in pixels
            hello.layoutParams.height = convertDpToPixel(randomHeightInDP, applicationContext)
             //refresh layout
            hello.requestLayout()
    
    
        }
    

    Convert DP to pixels, see this post:

    fun convertDpToPixel(dp: Float, context: Context): Int {
            return (dp * (context.resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)).toInt()
        }
    

提交回复
热议问题