2
3 import java.util.ArrayList;
4
5 import android.content.Context;
6 import android.util.AttributeSet;
7 import android.view.MotionEvent;
8 import android.view.View;
9 import android.view.ViewGroup;
10 import android.widget.HorizontalScrollView;
11 /**
12 *
13 * @author XINYE
14 *
15 */
16 public class MyScrollView extends HorizontalScrollView {
17 private int subChildCount = 0 ;
18 private ViewGroup firstChild = null ;
19 private int downX = 0 ;
20 private int currentPage = 0 ;
21 private ArrayList<integer> pointList = new ArrayList<integer>();
22
23 public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
24 super (context, attrs, defStyle);
25 init();
26 }
27
28
29 public MyScrollView(Context context, AttributeSet attrs) {
30 super (context, attrs);
31 init();
32 }
33
34 public MyScrollView(Context context) {
35 super (context);
36 init();
37 }
38 private void init() {
39 setHorizontalScrollBarEnabled( false );
40 }
41 @Override
42 protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
43 super .onMeasure(widthMeasureSpec, heightMeasureSpec);
44 receiveChildInfo();
45 }
46 public void receiveChildInfo() {
47
48 firstChild = (ViewGroup) getChildAt( 0 );
49 if (firstChild != null ){
50 subChildCount = firstChild.getChildCount();
51 for ( int i = 0 ;i < subChildCount;i++){
52 if (((View)firstChild.getChildAt(i)).getWidth() > 0 ){
53 pointList.add(((View)firstChild.getChildAt(i)).getLeft());
54 }
55 }
56 }
57
58 }
59 @Override
60 public boolean onTouchEvent(MotionEvent ev) {
61 switch (ev.getAction()) {
62 case MotionEvent.ACTION_DOWN:
63 downX = ( int ) ev.getX();
64 break ;
65 case MotionEvent.ACTION_MOVE:{
66
67 } break ;
68 case MotionEvent.ACTION_UP:
69 case MotionEvent.ACTION_CANCEL:{
70 if ( Math.abs((ev.getX() - downX)) > getWidth() / 4 ){
71 if (ev.getX() - downX > 0 ){
72 smoothScrollToPrePage();
73 } else {
74 smoothScrollToNextPage();
75 }
76 } else {
77 smoothScrollToCurrent();
78 }
79 return true ;
80 }
81 }
82 return super .onTouchEvent(ev);
83 }
84
85 private void smoothScrollToCurrent() {
86 smoothScrollTo(pointList.get(currentPage), 0 );
87 }
88
89 private void smoothScrollToNextPage() {
90 if (currentPage < subChildCount - 1 ){
91 currentPage++;
92 smoothScrollTo(pointList.get(currentPage), 0 );
93 }
94 }
95
96 private void smoothScrollToPrePage() {
97 if (currentPage > 0 ){
98 currentPage--;
99 smoothScrollTo(pointList.get(currentPage), 0 );
100 }
101 }
102 /**
103 * 下一页
104 */
105 public void nextPage(){
106 smoothScrollToNextPage();
107 }
108 /**
109 * 上一页
110 */
111 public void prePage(){
112 smoothScrollToPrePage();
113 }
114 /**
115 * 跳转到指定的页面
116 * @param page
117 * @return
118 */
119 public boolean gotoPage( int page){
120 if (page > 0 && page < subChildCount - 1 ){
121 smoothScrollTo(pointList.get(page), 0 );
122 currentPage = page;
123 return true ;
124 }
125 return false ;
126 }
127 }</integer></integer>
|