我有一个水平滚动的RecyclerView,上面设置了一些初始高度,在用户操作时,它的高度会发生变化。我想让回收器中的物品使用它们父对象的新边界,但它们似乎保持了以前确定的高度。
一个简单的例子:
<!-- RecyclerView's layout (the parent) -->
<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Guideline
android:id="@+id/guideline_top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.30" />
<Guideline
android:id="@+id/guideline_bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.90" />
<RecyclerView
android:id="@+id/my_recycler"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_manager="LinearLayoutManager"
app:layout_constraintTop_toTopOf="@id/guideline_top"
app:layout_constraintBottom_toBottomOf="@id/guideline_bottom"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</ConstraintLayout>
上面的回收器的高度将是其母尺寸的60%。
这是viewholders的布局:
<!-- Viewholder layout (the children) -->
<ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Test"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="At the bottom"
android:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</ConstraintLayout>
如果我以编程方式更改指南(例如,在用户按下某个按钮之后):
// Change top from 30% to 10%, and bottom from 90% to 100%
// New size is 80% of parent
guidelineTop.setGuidelinePercent(0.1f)
guidelineBottom.setGuidelinePercent(1f)
回收器视图自动设置动画并调整为正确的大小(父高度的80%),但它的子布局仍然布局,就好像回收器是(现在不正确的)父高度的60%。
我试着调用recyclerView.requestLayout()
,但似乎没有任何作用。我也尝试过为所有的孩子调用holder.itemView.requestLayout()
,但似乎也没有什么效果。
谁能告诉我如何让孩子们根据回收商拥有的新高度值调整自己的大小?
编辑:我可以看到子itemView的高度被更新了,但是子元素的位置并没有相应地表现出来。即,应该底部对齐的按钮不是。
发布于 2019-08-27 22:03:59
修复方法是在过渡/动画完成后重新应用约束。
// Once the animation is done, for each viewholder:
ConstraintSet()
.also { it.clone(constraintLayout) }
.applyTo(constraintLayout)
发布于 2019-08-26 03:45:49
我不确定,但我希望它能帮上忙
在更改高度后写下这一行:adapter.notifyDataSetChanged();
adapter
是您的回收器视图适配器
发布于 2019-08-26 08:55:51
在您将更改通知适配器之后,可能没有调用适配器的onCreateViewHolder()
来构建视图。
尝试覆盖适配器的getItemViewType()
,这将强制适配器在更新时调用onCreateViewHolder()
:
// Override this to force onCreateViewHolder to be called when appropriately notified
@Override
public int getItemViewType(int position){
return position; // Return any variable as long as it's not a constant value
}
然后,在更新大小后调用adapter.notifyDataSetChanged()
。
https://stackoverflow.com/questions/57647340
复制相似问题