【发布时间】:2018-05-23 14:17:14
【问题描述】:
我有一个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>
【问题讨论】:
-
虽然看不懂要求,但是因为布局pass在onBindViewHolder中没有完成,所以宽度为0。您可以使用它来检测该事件:developer.android.com/reference/android/view/…。一旦完成,它应该返回非零宽度。
-
但我还是不明白你为什么需要这个。例如,如果你有 2 个按钮,一个有很长的文本,一个有很短的文本,根据你的逻辑上,您将它们的大小设置为屏幕的 50%。在这种情况下,长按钮文本可能会被截断。这是预期的吗?
标签: android android-recyclerview kotlin