astro.zombi
astro.zombi

Reputation: 17

Kotlin: Setting width using view.layoutparams.width doesn't work

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

Answers (1)

Mayur
Mayur

Reputation: 358

Try this

val params: LinearLayout.LayoutParams = views.myView.layoutParams as LinearLayout.LayoutParams
        params.width = 500
        views.myView.layoutParams = params

Upvotes: 1

Related Questions