Margins of a LinearLayout, programmatically with dp

后端 未结 6 1879
生来不讨喜
生来不讨喜 2020-12-01 01:12

Is it possible to set the Margins of a LinearLayout, programmatically but not with pixels, but dp?

6条回答
  •  一生所求
    2020-12-01 02:08

    Well for the kotlin guys i have got handy helper fun which works perfectly :)

    fun setMarginsInDp(v: View, l: Int, t: Int, r: Int, b: Int) {
        if (v.layoutParams is ViewGroup.MarginLayoutParams){
            val screenDensity: Float = v.context.resources.displayMetrics.density
            val params: ViewGroup.MarginLayoutParams = v.layoutParams as ViewGroup.MarginLayoutParams
            params.setMargins(l*screenDensity.toInt(), t*screenDensity.toInt(), r*screenDensity.toInt(), b*screenDensity.toInt())
            v.requestLayout()
        }
    }
    

    Just pass in a valid view and all set up!

提交回复
热议问题