Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling issues with a ListView inside a ScrollView

Tags:

android

Here's the scenario conceptually (excluding linearlayouts)

ScrollView
  Button
  Checkboxes
  Spinner
  ListView (full-size, non-scrolling)
AdMob advert

i.e. a scrolling pane, which has a filtering UI at the top, followed by results, but the advert must always remain visible, and when scrolling down the filter UI must scroll away, leaving maximum space for results.

I'm aware there are issues with a ListView inside a ScrollView, though for me it is working well in many ways (I'm fixing the length of the ListView to stop it collapsing). So the screen scrolls nicely, the ad stays put at the bottom, and it looks good.

But the problem I'm seeing is, inexplicably, when the activity opens, the ScrollView is scrolled down a bit, so the ListView is at the top of the screen. I assume this is a default behaviour, so I set about trying to force the scroll position of the ScrollView to the top, but I've tried various methods, and see no effect:

scrollview.scrollTo(0, 1000/-1000);
scrollview.smoothScrollBy(0, 1000/-1000);
scrollview.fullScroll(View.FOCUS_UP);

Is there any way to force the ScrollView to start with the scroll position at the top?

If not, how can I have an ad that doesn't scroll off the bottom, but a filter UI that always scrolls off the top? Using ListView seems overkill as I don't need scrolling but it does provide many benefits so would be nice to avoid starting from scratch and rendering everything myself.

like image 424
Ollie C Avatar asked Oct 24 '10 19:10

Ollie C


1 Answers

Use the following method and enjoy!

    private void setListViewScrollable(final ListView list) {
    list.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            listViewTouchAction = event.getAction();
            if (listViewTouchAction == MotionEvent.ACTION_MOVE)
            {
                list.scrollBy(0, 1);
            }
            return false;
        }
    });
    list.setOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view,
                int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            if (listViewTouchAction == MotionEvent.ACTION_MOVE)
            {
                list.scrollBy(0, -1);
            }
        }
    });
}

listViewTouchAction is a global integer value. If you can replace the line

list.scrollBy(0, 1);

with something else please share it with us.

like image 80
Bobs Avatar answered Oct 21 '22 00:10

Bobs