Is there any way to get a listview overscroll on Android 2.2 or 2.1?
Is there any way to get a listview overscroll on Android 2.2 or 2.1?
I have used overscroll in开发者_运维技巧 Android 2.3 but its not running in 2.2. How can I achieve that?
Create an "overscroll" view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<View
android:layout_width="fill_parent"
android:layout_height="320px"
android:background="@android:color/transparent"
/>
</LinearLayout>
You need some global variables in the main activity:
private int currentScrollState = OnScrollListener.SCROLL_STATE_IDLE;
// itemAtTop and itemOffset are needed for when the listview doesn't have enough items to fill the screen
private int itemAtTop = 0, itemOffset = 0; // reset both to 0 each time you populate the listview
private Handler mHandler = new Handler();
In main activity's onCreate, before setting the listview's adapter, add header and footer:
View v = LayoutInflater.from(this).inflate(R.layout.listview_overscrollview, null);
listview.addHeaderView(v, null, false);
listview.addFooterView(v, null, false);
listview.setOnScrollListener(this);
Your main activity has to override 2 methods because of the setOnScrollListener:
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
checkTopAndBottom();
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
currentScrollState = scrollState;
checkTopAndBottom();
}
The checkTopAndBottom() function, which should also be called after the listview is (re)populated:
public void checkTopAndBottom()
{
if ( listview.getCount() <= 2 ) return; // do nothing, only header and footer in listview
if ( scrollState != OnScrollListener.SCROLL_STATE_IDLE ) return; // do nothing, listview still scrolling
if ( listview.getFirstVisiblePosition() < 1 ) {
listview.setSelectionFromTop(1, -1);
}
if ( listview.getLastVisiblePosition() == listview.getCount()-1 ) {
listview.setSelectionFromTop(listview.getCount()-1, listview.getHeight());
}
mHandler.post(checkListviewBottom);
}
And finally the runnable ( for the listview.getFirstVisiblePosition(), etc to be up to date ):
private final Runnable checkListviewBottom = new Runnable()
{
@Override
public void run() {
if ( listview.getLastVisiblePosition() == listview.getCount()-1 ) {
if ( itemAtTop == 0 ) {
if ( listview.getFirstVisiblePosition() <= 1 ) {
itemAtTop = 1;
itemOffset = -1;
} else {
itemAtTop = listview.getCount()-1;
itemOffset = listview.getHeight()+1;
}
}
if ( itemAtTop == listview.getCount()-1 || (itemAtTop == 1 && listview.getFirstVisiblePosition() > 0) ) {
listview.setSelectionFromTop(itemAtTop, itemOffset);
}
}
}
};
精彩评论