You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin设置View宽度报错:Val cannot be reassigned

Fixing "Val cannot be reassigned" When Setting View Width in Kotlin

Got it, this is a super common gotcha when you're starting out with Kotlin for Android development! Let me break down why you're seeing this error and how to fix it.

Why the error happens

The shadowView.width property is a read-only calculated property (it maps to the Java getter getWidth() under the hood). It only returns the current actual width of the View—it's not designed to let you set the width directly. That's why Kotlin marks it as a val, which can't be reassigned.

The correct way to set View width dynamically

To change the width of your View, you need to modify its LayoutParams instead. Here's how to do it in your Activity's onCreate() method:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.your_layout)
    
    val shadowView = findViewById<View>(R.id.shadowView)
    
    // Get the current LayoutParams of the View
    val layoutParams = shadowView.layoutParams
    // Set the desired width (200 here is in pixels)
    layoutParams.width = 200
    // Apply the updated LayoutParams back to the View
    shadowView.layoutParams = layoutParams
}

Bonus: Use dp instead of raw pixels

If you want to use dp units (which is recommended for responsive UI across different devices), add a helper function to convert dp to pixels:

fun Context.dpToPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

Then use it like this:

layoutParams.width = dpToPx(200) // Sets width to 200dp

This works because every View has LayoutParams that define how it's laid out within its parent container. By modifying these params and reassigning them, you're telling the parent layout to update the View's size properly.

内容的提问来源于stack exchange,提问作者Jayakrishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:32:59