如何在recyclerview中找到项目的宽度?
我有一个 recyclerview
,它只是按钮的水平列表.我正在尝试创建以下行为:
I have a recyclerview
which is just a horizontal list of buttons. I am trying to create the following behavior:
如果组合的所有按钮的总宽度小于屏幕的总宽度,请将每个按钮的宽度设置为(screenWidth/按钮数).
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).
我正在测试一些基本代码来获取/设置按钮宽度,例如在我的 adapter
类中:
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)
}
}
奇怪的是,虽然此代码实际上将按钮的宽度更改为1080,但在设置按钮宽度之前/之后,两个 Log
函数的输出均为0.
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?
这是我的布局,在我的 recyclerview
中定义了一列:
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>
Android仅在测量后才返回小部件的宽度,并且发生时间晚于调用 onBindViewHolder
的时间.
Android returns width of the widget only after it is measured and it happens later than onBindViewHolder
is called.
您可以延迟请求:
holder.button.post {
Log.d("VED-APP","New Button Width: " + holder.button.width.toString())
};