@Gallery配合dot使用时,如果放在RelativeLayout中,则手动滑动有反弹现象,其他layout没问题,现在还没弄清原因。
首先继承Gallery重写OnFling函数,去除gallery的滚动惯性

 
  
  1. public class MyGallery extends Gallery { 
  2.  
  3.     public MyGallery(Context context, AttributeSet attrs) { 
  4.         super(context, attrs); 
  5.         // TODO Auto-generated constructor stub 
  6.     } 
  7.  
  8.     private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) { 
  9.  
  10.         return e2.getX() > e1.getX(); 
  11.  
  12.     } 
  13.      
  14.     @Override 
  15.     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
  16.             float velocityY) { 
  17.         int keyCode; 
  18.  
  19.         if (isScrollingLeft(e1, e2)) { 
  20.  
  21.             keyCode = KeyEvent.KEYCODE_DPAD_LEFT; 
  22.  
  23.         } else { 
  24.  
  25.             keyCode = KeyEvent.KEYCODE_DPAD_RIGHT; 
  26.  
  27.         } 
  28.  
  29.         onKeyDown(keyCode, null); 
  30.  
  31.         return true
  32.     } 
  33.  

@ OnFling直接返回false也能实现类似效果,但那样需要滑动很大距离,图片才会切换,用户体验不好

 

第二步,构造adapter

要想平滑的实现循环滚动,可以让getCount返回一个很大的值,这样gallery就认为是有多个item,item之间的切换动画是平滑的

 
  
  1. public class GalleryAdapter extends BaseAdapter { 
  2.  
  3.     private LayoutInflater mInflater; 
  4.     private Context mContext; 
  5.     private int width; 
  6.     private int count; 
  7.     private int[] mImageIds; 
  8.  
  9.     public GalleryAdapter(Context context, int[] ids) { 
  10.         mContext = context; 
  11.         mImageIds = ids; 
  12.         mInflater = LayoutInflater.from(mContext); 
  13.         DisplayMetrics dm = mContext.getApplicationContext().getResources() 
  14.                 .getDisplayMetrics(); 
  15.         width = dm.widthPixels; 
  16.         count = mImageIds.length; 
  17.     } 
  18.  
  19.     @Override 
  20.     public int getCount() { 
  21.         return Integer.MAX_VALUE;//用于循环滚动 
  22.     } 
  23.  
  24.     @Override 
  25.     public Object getItem(int position) { 
  26.         return position; 
  27.     } 
  28.  
  29.     @Override 
  30.     public long getItemId(int position) { 
  31.         return position; 
  32.     } 
  33.  
  34.     @Override 
  35.     public View getView(int position, View convertView, ViewGroup parent) { 
  36.         position = position % count; 
  37.         if (convertView == null) { 
  38.             convertView = mInflater.inflate(R.layout.gallery_item, null); 
  39.         } 
  40.         ImageView v = (ImageView) convertView.findViewById(R.id.img); 
  41.         v.setLayoutParams(new Gallery.LayoutParams(width, 200)); 
  42.         v.setScaleType(ImageView.ScaleType.FIT_XY); 
  43.         v.setBackgroundResource(mImageIds[position]); 
  44.         return v; 
  45.     } 
  46.