Reputation: 17
I am trying to change width of a view programmatically, but it doesn't work, nothing changes. This is the code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myFragmentLayout"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:orientation="horizontal">
<View
android:id="@+id/myView"
android:layout_width="10dp"
android:layout_height="50dp" />
And in my fragment, I try this:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val views = FragmentMyBinding.bind(view)
views.myView.layoutParams.width = 500
I tried using viewTreeObserver, but still nothing happens:
views.myView.viewTreeObserver.addOnGlobalLayoutListener(
object : OnGlobalLayoutListener {
override fun onGlobalLayout() {
view.viewTreeObserver
.removeOnGlobalLayoutListener(this)
views.myView.updateLayoutParams {
width = 500
}
}
})
Seems like I am calling layoutParams on a wrong layout for some reason
Upvotes: 0
Views: 349
Reputation: 358
Try this
val params: LinearLayout.LayoutParams = views.myView.layoutParams as LinearLayout.LayoutParams
params.width = 500
views.myView.layoutParams = params
Upvotes: 1