如何在RecyclerView中查找项目的宽度?

5
我有一个recyclerview,它只是一个水平按钮列表。我想要创建以下行为:
如果所有按钮的总宽度小于屏幕的总宽度,则将每个按钮的宽度设置为(屏幕宽度/按钮数)。
我正在测试一些基本代码来获取/设置按钮宽度,例如在我的adapter类中:
 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)
        }
    }

奇怪的是,虽然这段代码确实将按钮的宽度更改为1080,但在设置按钮宽度之前/之后的两个Log函数的输出都为0。

我该如何获取按钮的实际宽度?

以下是定义我的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>

虽然我不理解需求,但宽度为0是因为在onBindViewHolder中布局传递没有完成。您可以使用此代码来检测该事件:https://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener。一旦完成,它应该返回非零宽度。 - Gennadii Saprykin
但我仍然不明白为什么你需要这个...例如,如果你有两个按钮,一个文本非常长,另一个文本非常短,但都适合屏幕大小,按照你的逻辑,你会将它们的大小设置为屏幕的50%。在这种情况下,长按钮文本可能会被截断。这是预期的吗? - Gennadii Saprykin
1个回答

8

在 Android 中,小部件的宽度只有在其被测量后才会返回,这通常发生在调用 onBindViewHolder 函数之后。

你可以延迟请求:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接