Android Kotlin设置View宽度报错:Val cannot be reassigned
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

