本文实例讲述了android实现自动滚动的Gallary控件。分享给大家供大家参考。具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;
public class HomeGallery extends Gallery
{
/**
* 这里的数值,限制了每次滚动的最大长度,图片宽度为480PX。这里设置600效果好一些。 这个值越大,滚动的长度就越大。
* 也就是会出现一次滚动跨多个Image。这里限制长度后,每次滚动只能跨一个Image
*/
private static final int timerAnimation = 1 ;
private static final int time = 2000 ;
private final Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case timerAnimation:
int position = getSelectedItemPosition();
Log.i( "msg" , "position:" +position);
if (position >= (getCount() - 1 ))
{
onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null );
} else
{
onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null );
}
break ;
default :
break ;
}
};
};
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask()
{
public void run()
{
mHandler.sendEmptyMessage(timerAnimation);
}
};
public HomeGallery(Context paramContext)
{
super (paramContext);
timer.schedule(task, time, time);
}
public HomeGallery(Context paramContext, AttributeSet paramAttributeSet)
{
super (paramContext, paramAttributeSet);
timer.schedule(task, time, time);
}
public HomeGallery(Context paramContext, AttributeSet paramAttributeSet,
int paramInt)
{
super (paramContext, paramAttributeSet, paramInt);
timer.schedule(task, time, time);
}
private boolean isScrollingLeft(MotionEvent paramMotionEvent1,
MotionEvent paramMotionEvent2)
{
float f2 = paramMotionEvent2.getX();
float f1 = paramMotionEvent1.getX();
if (f2 > f1)
return true ;
return false ;
}
public boolean onFling(MotionEvent paramMotionEvent1,
MotionEvent paramMotionEvent2, float paramFloat1, float paramFloat2)
{
int keyCode;
if (isScrollingLeft(paramMotionEvent1, paramMotionEvent2))
{
keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
} else
{
keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
}
onKeyDown(keyCode, null );
return true ;
}
public void destroy()
{
timer.cancel();
}
}
|
希望本文所述对大家的Android程序设计有所帮助。