mol*_*may 4 android listview fastscroll
有没有办法检测ListView是否快速滚动?也就是说,我们可以知道用户何时按下并释放FastScroller?
反射允许你这样做.通过查看AbsListView源代码,有一个FastScroller对象指示快速滚动功能的包装器.它的源代码显示了一个有趣的领域:
/**
* Current decoration state, one of:
* <ul>
* <li>{@link #STATE_NONE}, nothing visible
* <li>{@link #STATE_VISIBLE}, showing track and thumb
* <li>{@link #STATE_DRAGGING}, visible and showing preview
* </ul>
*/
private int mState;
Run Code Online (Sandbox Code Playgroud)
该字段包含FastScroller对象的状态.解决方案包括每次触发onScroll()和onScrollStateChanged()方法时通过反射读取该字段的值.
此代码实现上述解决方案:
private class CustomScrollListener implements OnScrollListener {
private ListView list;
private int mState = -1;
private Field stateField = null;
private Object mFastScroller;
private int STATE_DRAGGING;
public CustomScrollListener() {
super();
String fastScrollFieldName = "mFastScroller";
// this has changed on Lollipop
if (Build.VERSION.SDK_INT >= 21) {
fastScrollFieldName = "mFastScroll";
}
try {
Field fastScrollerField = AbsListView.class.getDeclaredField(fastScrollFieldName);
fastScrollerField.setAccessible(true);
mFastScroller = fastScrollerField.get(list);
Field stateDraggingField = mFastScroller.getClass().getDeclaredField("STATE_DRAGGING");
stateDraggingField.setAccessible(true);
STATE_DRAGGING = stateDraggingField.getInt(mFastScroller);
stateField = mFastScroller.getClass().getDeclaredField("mState");
stateField.setAccessible(true);
mState = stateField.getInt(mFastScroller);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// update fast scroll state
try {
if (stateField != null) {
mState = stateField.getInt(mFastScroller);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (mState == STATE_DRAGGING)) {
// the user is fast scrolling through the list
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// update fast scroll state
try {
if (stateField != null) {
mState = stateField.getInt(mFastScroller);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用 setOnScrollListener 并实现 onScrollStateChanged。滚动状态可以是空闲、触摸滚动或滑动
setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
if(scrollState == 2) Log.i("a", "fast scroll");
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1655 次 |
| 最近记录: |