0

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

1 Answer 1

1

Try this

val params: LinearLayout.LayoutParams = views.myView.layoutParams as LinearLayout.LayoutParams
        params.width = 500
        views.myView.layoutParams = params
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, nice idea, but still nothing, doesnt change

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.