我正在设计一个聊天应用。当我滚动到顶部并到达末尾时,我想加载更多以前的消息,问题是当我在顶部添加视图时(同一用户已经到达顶部),滚动视图跳转到顶部。
我很快想出了可行的解决方案,但看起来很糟糕,因为您可以在一毫秒内看到它是如何跳跃的,而我需要以用户不会注意到的方式进行操作。
我的错误解决方案(跳跃在 1 帧中可见):
int beforeHeight = messagesLinearLayout.getBottom();
for (int i = 0; i < 10; i++)
{
messagesLinearLayout.addView(view, 0);
}
messagesLinearLayout.requestLayout();
messagesLinearLayout.post(new Runnable() {
@Override
public void run() {
int afterHeight = messagesLinearLayout.getBottom() - beforeHeight;
messagesScrollView.scrollTo(0, afterHeight);
}
});
布局:
<ScrollView
android:id="@+id/messagesScrollView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="-15dp"
android:focusableInTouchMode="true"
app:layout_constraintBottom_toTopOf="@+id/cardView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/appBarLayout">
<LinearLayout
android:id="@+id/messagesLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusableInTouchMode="true"
android:paddingBottom="20dp"
android:paddingTop="5dp"
android:orientation="vertical"
android:focusable="true" />
</ScrollView>
有什么办法可以让它不显眼?也许还有其他解决方案。
答案 0 :(得分:1)
我建议使用回收器视图而不是具有线性布局的滚动视图。它将运行得更快,因为它会为下一个视图回收使用过的布局/视图,确保即使有 1000 个项目,也不会超过 10 个视图。
可以在此处找到有关如何使用回收器视图的一些示例:https://developer.android.com/guide/topics/ui/layout/recyclerview
我推荐的另一个选项是默认的 ListView,效果也很好。