Kotlin中使用view.layoutParams.width设置View宽度无效问题
解决动态修改View宽度无效的问题
核心问题分析
你的代码存在两个关键问题:
- 直接修改
layoutParams.width后,未通知View重新布局,系统不会自动刷新尺寸 - 使用
viewTreeObserver时,移除监听器的对象错误(应该操作目标View的viewTreeObserver,而非根View的)
修复方案
方案1:直接修改LayoutParams并触发重绘
修改onViewCreated中的代码,修改宽度后调用requestLayout()通知系统重绘:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val views = FragmentMyBinding.bind(view) val params = views.myView.layoutParams params.width = 500 // 注意:此处单位为像素(px) views.myView.layoutParams = params // 或者直接调用requestLayout(),二选一即可 // views.myView.requestLayout() }
方案2:正确使用updateLayoutParams(推荐)
updateLayoutParams是Kotlin扩展函数,会自动触发重绘,但要确保监听器操作的是目标View:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val views = FragmentMyBinding.bind(view) views.myView.viewTreeObserver.addOnGlobalLayoutListener( object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { // 移除当前目标View的监听器,而非根View的 views.myView.viewTreeObserver.removeOnGlobalLayoutListener(this) views.myView.updateLayoutParams<LinearLayout.LayoutParams> { width = 500 // 单位为像素(px) } } }) }
额外注意事项
- 代码中的
500是像素单位,如果需要使用dp,需先做单位转换:fun dpToPx(dp: Int, context: Context): Int { return (dp * context.resources.displayMetrics.density).toInt() } // 使用示例:width = dpToPx(200, requireContext()) - 父布局
LinearLayout的layout_width设为wrap_content不影响子View宽度修改,无需调整父布局属性
内容的提问来源于stack exchange,提问作者astro.zombi
相关产品推荐
相关产品推荐

