在android中,我有一个按钮,当用户向上滚动时会出现,否则会消失。然而,当它出现时,我试图让它在3秒后再次消失,如果用户停止滚动(在空闲3秒后)。我尝试了以下代码,
//detecting whether the user is scrolling up or down, to make the refresh button visible/invisible
listView.setOnTouchListener(new View.OnTouchListener() {
int scrollEventListSize = 5;
float lastY;
// Used to correct for occasions when user scrolls down(/up) but the onTouchListener detects it incorrectly. We will store detected up-/down-scrolls with -1/1 in this list and evaluate later which occured more often
List<Integer> downScrolledEventsHappened;
@Override
public boolean onTouch(View v, MotionEvent event) {
float diff = 0;
if(event.getAction() == event.ACTION_DOWN){
lastY = event.getY();
downScrolledEventsHappened = new LinkedList<Integer>();
}
else if(event.getAction() == event.ACTION_MOVE){
diff = event.getY() - lastY;
lastY = event.getY();
if(diff>0)
downScrolledEventsHappened.add(1);
else
downScrolledEventsHappened.add(-1);
//List needs to be filled with some events, will happen very quickly
if(downScrolledEventsHappened.size() == scrollEventListSize+1){
downScrolledEventsHappened.remove(0);
int res=0;
for(int i=0; i<downScrolledEventsHappened.size(); i++){
res+=downScrolledEventsHappened.get(i);
}
if (res > 0) {
Log.i("INFO", "Scrolled up");
refreshButton.setVisibility(View.VISIBLE);
}
else {
Log.i("INFO", "Scrolled down");
refreshButton.setVisibility(View.INVISIBLE);
}
}
}
return false; // don't interrupt the event-chain
}
});
//Removing refresh button when user stops scrolling up or already at the top of the list.
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
refreshButton.setVisibility(View.INVISIBLE);
}
}, 3000);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem == 0 && listIsAtTop()){
System.out.println("List at Top....Refresh Button is disappearing...");
refreshButton.setVisibility(View.INVISIBLE);
}
}
});
然而,这段代码并没有完全给我我想要的东西。确实,用户在空闲3秒后按钮消失,但是当用户再次向上滚动时,按钮也会消失!我的意思是,我需要一种机制,当用户再次向上滚动时,3秒钟消失的想法将被取消。我怎样才能做到这一点?谢谢。
答案 0 :(得分:2)
当使用向上滚动时取消处理程序待处理事件并再次启动处理程序
类似这样的事情
myHandler.removeCallbacks(myRunnable);
以这种方式启动处理程序
myHandler.postDelayed(myRunnable,LENGTH);