添加手势监听:
1 GestureDetector detector;// 手势侦听
1 detector = new GestureDetector(getApplicationContext(),2 new myGestureListener());
手势侦听 在 onFling 中指定屏幕滑动效果和展示图像:
1 class myGestureListener implements OnGestureListener { 2 // 当触碰事件按下时触发该方法 3 @Override 4 public boolean onDown(MotionEvent event) { 5 return false; 6 } 7 8 // 用户在触摸屏上拖过时触发该方法 9 @Override10 public boolean onFling(MotionEvent event1, MotionEvent event2,11 float velocityX, float velocityY) {12 ((GridView) viewSwitcher.getNextView()).setAdapter(adapter);13 if (event2.getX() - event1.getX() > FLIP_DISTANCE) {14 if (screenNo > 0) {15 screenNo--;16 // 添加屏幕动画切换效果17 viewSwitcher.setInAnimation(animations[0]);18 viewSwitcher.setInAnimation(animations[3]);19 viewSwitcher.showPrevious();20 return true;21 } else {22 Toast.makeText(getApplicationContext(), "已无更多页面",23 Toast.LENGTH_LONG).show();24 }25 } else {26 if (screenNo < screenCount - 1) {27 screenNo++;28 viewSwitcher.setInAnimation(animations[1]);29 viewSwitcher.setInAnimation(animations[2]);30 viewSwitcher.showNext();31 return true;32 } else {33 Toast.makeText(getApplicationContext(), "已无更多页面",34 Toast.LENGTH_LONG).show();35 }36 }37 return false;38 }39 40 // 用户在屏幕上长按时触发该方法41 @Override42 public void onLongPress(MotionEvent event) {43 44 }45 46 // 用户在屏幕上滚动时触发该方法47 @Override48 public boolean onScroll(MotionEvent event1, MotionEvent event2,49 float velocityX, float velocityY) {50 return false;51 }52 53 // 用户在触摸屏上按下,而且还未移动和松开时触发该方法54 @Override55 public void onShowPress(MotionEvent arg0) {56 57 }58 59 // 用户在触屏上的轻击事件将触发该方法60 @Override61 public boolean onSingleTapUp(MotionEvent arg0) {62 return false;63 }64 65 }
进入的第一个界面展示 代码:
1 public void next(View v) { 2 if (screenNo == -1) { 3 screenNo++; 4 ((GridView) viewSwitcher.getNextView()).setAdapter(adapter); 5 viewSwitcher.showNext(); 6 } else { 7 Toast.makeText(getApplicationContext(), "已无更多页面", Toast.LENGTH_LONG) 8 .show(); 9 }10 }
定义BaseAdapter:
1 private BaseAdapter adapter = new BaseAdapter() { 2 @Override 3 public long getItemId(int position) { 4 return position; 5 } 6 7 @Override 8 public DataItem getItem(int position) { 9 return total.get(screenNo * Number_Per_Screen + position);10 }11 12 @Override13 public int getCount() {14 if (screenNo == screenCount - 115 && total.size() % Number_Per_Screen != 0) {16 return total.size() % Number_Per_Screen;17 }18 return Number_Per_Screen;19 }20 21 @Override22 public View getView(int position, View convertView, ViewGroup parent) {23 View view = convertView;24 if (convertView == null) {25 view = layoutInflater.inflate(R.layout.labelicon, null);26 }27 ImageView imageview = (ImageView) view.findViewById(R.id.imageview);28 imageview.setImageDrawable(getItem(position).drawable);29 TextView textView = (TextView) view.findViewById(R.id.textview);30 textView.setText(getItem(position).DataName);31 return view;32 }33 };
此处只是对 疯狂Android 讲义 中ViewSwitcher 的 手势 添加 做的一个小demo,本人处于初学阶段,如有不对的地方,请各位多多指正!!