Michael Brenndoerfer
Michael Brenndoerfer

Reputation: 4066

How to prevent flickering ListView when requesting Layout very often

I'm implementing a "parallax" effect which consists of a list view and an image view above. When the user scrolls downwards, the offset is subtracted from the height of the image view. This works fine. I'm doing this in the scroll listener of the list view. To really update the listview and imageview in realtime I need to call requestLayout().

The problem is, that this method is asynchronous and if I scroll slowly it flickers extremely. If I just swipe quickly it looks very nice. Is there an other solution to solve this?

ScrollListener

@Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            View c = view.getChildAt(0);
            int top = (c == null) ? 0 : (-c.getTop() + view.getFirstVisiblePosition() * c.getHeight());
            //Log.d(TAG, "Offset = " + top);
            mImageView.getLayoutParams().height = 400 - top;
            mImageView.requestLayout();
        }

Layout

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:context="xxx.fragments.NewsFragment">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@android:color/holo_blue_light"
    android:id="@+id/advertisement"
    />

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/news_feed">

</ListView>

</TableLayout>

enter image description here

Upvotes: 0

Views: 782

Answers (1)

Karakuri
Karakuri

Reputation: 38595

If you just want the ImageView to scroll with the list, then you can simply add it as a header view:

listView.addHeaderView(mImageView);

Make sure you call this method before calling setAdapter. Also make sure your ImageView doesn't already have a parent, so inflate it separately or just create one in code using new ImageView.

Upvotes: 2

Related Questions