gpt4 book ai didi

android - 如何检测 ListView 是否正在快速滚动

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:27 24 4
gpt4 key购买 nike

有没有办法检测 ListView 是否正在快速滚动?也就是说,我们能否以某种方式知道用户何时按下和释放 FastScroller?

最佳答案

反射可以让你做到这一点。通过查看 AbsListView source code ,有一个 FastScroller 对象,它指示围绕快速滚动功能的包装器。 Its source code显示一个有趣的 field :

/**
* 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;

此字段包含 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();
}

}
}

关于android - 如何检测 ListView 是否正在快速滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com