如何在recyclerview中找到项目的宽度?

Roy*_*son 4 android kotlin android-recyclerview

我有一个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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

奇怪的是,虽然这段代码确实将按钮的宽度更改为 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>
Run Code Online (Sandbox Code Playgroud)

Tpo*_*6oH 6

Android 仅在测量后才返回小部件的宽度,并且它发生的时间晚于onBindViewHolder调用。

您可以延迟请求:

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