Android - Scroll/Move the ListView itself

2019-02-25 02:10发布

问题:

I have seen some modern Android and iOS applications where there will be an Image at the top of the page that covers the entire width of the screen. Beneath it, there will be a ListView that stretches all the way down to the page.

When you start to scroll downwards on the ListView, the ListView itself starts to move upwards until it hits the top of the screen, i.e. completely covering the top screen.

Examples of apps that do this are: Google Play Store, Huffington Post, YouTube.

I've tried googling this but haven't managed to find an relative source.

回答1:

This is a bit of visual trickery, where it seems as the image and list are one but they are really not.

basically you have a listview with a headerview the same size as the image and below the listview you have your image so as you scroll it appears the listview is scrolling over the image.

The layout would look something like this

<RelativeLayout>

    <ImageView></ImageView>

    <ListView></ListView>

</RelativeLayout>

The create another layout for the header that is empty with the size of the imageview

You can also Translate the image in the Y direction when the list scrolls but then you have to hold onto the view globally in your class so you can translate using v.setTranslateY()



回答2:

You need to add a header to the listview. You can do it by doing this:

final View header = LayoutInflater.from(getActivity()).inflate(R.layout.myheader, null);
((ListView) getActivity().findViewById(R.id.list)).addHeader(header);

Then you can do the scroll effect by doing this:

    ((ListView) getActivity().findViewById(R.id.list)).setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (v.getChildCount() > 0 && v.getChildAt(0) != null)
                header.setTranslationY(Math.round(-v.getChildAt(0).getTop() * 0.5));
        }
    });

Here header is the header of the listview