5

I have a recyclerview which is just a horizontal list of buttons. I am trying to create the following behavior:

If the total width of all of the buttons combined is less than the total width of the screen, set the width of each button to (screenWidth/number of buttons).

I am testing some basic code to get/set button widths like so in my adapter class:

 override fun onBindViewHolder(holder: TabViewHolder, position: Int) {

        Log.d("TEST-APP","Button Width: " + holder.button.width.toString())

        holder.button.width = 1080

        Log.d("VED-APP","New Button Width: " + holder.button.width.toString())

        holder.button.text = items[position].first
        holder.button.setOnClickListener {
            (context as MainActivity).updateCurrentImageLayout(items[position].second)
        }
    }

The odd thing is, while this code does actually change the width of the button to 1080 the outputs of the two Log functions before/after setting the button width are both 0.

How do I get the actual width of the button?

Here is my layout which defines one column in my recyclerview:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/tabButton"
        android:layout_width="match_parent"
        android:minWidth="120dp"
        android:layout_height="match_parent"
        android:text="Unset-Button-Text"/>


</android.support.constraint.ConstraintLayout>
Foobar
  • 7,458
  • 16
  • 81
  • 161
  • Although I don't understand the requirements, the width is 0 because the layout pass did not finish in onBindViewHolder. You can use this for detecting that event: https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener. Once this finishes it should return you non-zero width. – Gennadii Saprykin May 23 '18 at 14:54
  • But I still don't understand why you need this.. E.g if you have 2 buttons, one with a very long text and one with a very short one which DO fit the screen, according to your logic you will set their size to 50% of the screen.. The long button text might be cut-off in this case. Is this expected? – Gennadii Saprykin May 23 '18 at 14:54

1 Answers1

8

Android returns width of the widget only after it is measured and it happens later than onBindViewHolder is called.

You can delay the request:

holder.button.post {
    Log.d("VED-APP","New Button Width: " + holder.button.width.toString()) 
};
TpoM6oH
  • 8,385
  • 3
  • 40
  • 72