1、设置控件高宽
topBg.layoutParams.height=130 //重新设置背景框高度
topBg.layoutParams.width=130 //重新设置背景框宽度
注意:topBg是控件的id,此时130的单位是px。如果不介意单位是px的话,直接这样用也是没有问题的。
2、用Kotlin编写单位转换的方法
//根据手机的分辨率从 dp 的单位 转成为 px(像素)
fun dip2px(context: Context, dpValue: Int): Int {
val scale = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
//根据手机的分辨率从 px(像素) 的单位 转成为 dp
fun px2dip(context: Context, pxValue: Int): Int {
val scale = context.resources.displayMetrics.density
return (pxValue / scale + 0.5f).toInt()
}
3、实现layoutParams单位的转换
topBg.layoutParams.height=dip2px(context,130) //重新设置背景框高度
topBg.layoutParams.width=dip2px(context,130) //重新设置背景框宽度
注意:此时130的单位是dp,经过 dip2px(context,130)转换后,得出的数值单位是px
4、参考链接: https://blog.csdn.net/Wind_waving/article/details/104741516