业务需要,需要在Gallery中实现定时循环滚动效果,而网上的大部分资料都是循环跳动,没有像屏幕拖动那种效果,经过几天的研究和资料整合,找出了解决方法。
首先定时循环:
ScheduledThreadPoolExecutor timer = (ScheduledThreadPoolExecutor) Executors
.newScheduledThreadPool(1);
ImageTask imageTask = new ImageTask();
timer.scheduleAtFixedRate(imageTask, 0, 8, TimeUnit.SECONDS);
private class ImageTask extends TimerTask {
public void run() {
// getPos是我在imageAdapter中加入的方法,在ImageAdapter加一个成员变量position,然后在getView中将position
的值负值给成员变量,getPos()返回这个成员变量值
int curPos = imageAdapter.getPos();
Message message2 = new Message();
Bundle data = new Bundle();
data.putInt("pos", curPos);
message2.what = 1;
message2.setData(data);
myHandler.sendMessage(message2);
}
然后在Handler对象中处理:
imageAdapter.setCount(focusList.size());
focusGallery.setAdapter(imageAdapter);
//注意,这两个事件是我模拟处理的,其中的数字是我用用手拖动然后用在实际Gallery的onFling事件Log打印出来的。
想实现定时有一个假象的拖动动作,就模拟了这两个事件。
MotionEvent e1 = MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_DOWN, 322.25406f, 108.34271f, 0);
MotionEvent e2 = MotionEvent.obtain(
SystemClock.uptimeMillis(),
SystemClock.uptimeMillis(),
MotionEvent.ACTION_MOVE, 146.52338f, 122.55939f, 0);
//这里一定要使用setSelection,否则每次都会从第一张图片滚动,也就是说只要速度正常,只出现第一张和第二张图片
选择当前图片,然后在当前位置下滚动。
focusGallery.setSelection(msg.getData().getInt("pos"));
if(firstLoad){
firstLoad = false;
}else{
//-945这个值可以自己测试做相应的调整,负值表示向右滑动
focusGallery.onFling(e1, e2, -945, 0);
}
addHeaderPointImage(focusList.size());
}
然后在Gallery的Adapter中然getCount()返回Integer.MAX_VALUE;在getView中position参数进行如下处理
int imageSize = focusList.size();
position = position % imageSize;
然后就可以无限循环了。
最后处理一下那个圆点。
focusGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> paramAdapterView,
View paramView, int paramInt, long paramLong) {
int curPos = imageAdapter.getPos();
paramInt = curPos % focusList.size();
Log.v("liuyx", curPos+"");
for (int i = 0; i < pointImageList.size(); i++) {
if (paramInt == i) {
pointImageList.get(i).setImageResource(
R.drawable.information_focus_cirlce_current);
} else {
pointImageList.get(i).setImageResource(
R.drawable.information_focus_cirlce);
}
}
}
public void onNothingSelected(AdapterView<?> paramAdapterView) {
}
});