gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:01:53 24 4
gpt4 key购买 nike

我有一个 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>

最佳答案

Android 仅在测量后返回小部件的宽度,并且发生在调用 onBindViewHolder 之后。

您可以延迟请求:

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

关于android - 如何在 recyclerview 中找到项目的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50490737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com