简体   繁体   中英

Scroll view jumps to top when I add view at top

Im designing a chat app. When I scroll to top and reach the end I want to load more previous messages, the problem is when I add view at the top (at the same user already reached top), the scroll view jumps to top.

I quickly came up with solution that works, but looks bad because you can see for a milisecond how it jumps and I need to do it the way user won't notice.

My buggy solution (jump is visible in 1 frame):

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);
    }
});

Layout:

<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>

Is there any way to make it not noticable? Maybe there is another solution.

I recommend using a recycler view instead of a scrollview with a linear layout. It will run much faster as it recycles used layouts/views for the next view insuring there are never more than lets say 10 views even if there are 1000 items.

Some examples on how to use recylcer view can be found here: https://developer.android.com/guide/topics/ui/layout/recyclerview

Another option I would recommend is the default ListView, works pretty nicely as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM