@Gallery配合dot使用时,如果放在RelativeLayout中,则手动滑动有反弹现象,其他layout没问题,现在还没弄清原因。
首先继承Gallery重写OnFling函数,去除gallery的滚动惯性
- public class MyGallery extends Gallery {
- public MyGallery(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- }
- private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
- return e2.getX() > e1.getX();
- }
- @Override
- public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
- float velocityY) {
- int keyCode;
- if (isScrollingLeft(e1, e2)) {
- keyCode = KeyEvent.KEYCODE_DPAD_LEFT;
- } else {
- keyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
- }
- onKeyDown(keyCode, null);
- return true;
- }
- }
@注 OnFling直接返回false也能实现类似效果,但那样需要滑动很大距离,图片才会切换,用户体验不好
第二步,构造adapter
要想平滑的实现循环滚动,可以让getCount返回一个很大的值,这样gallery就认为是有多个item,item之间的切换动画是平滑的
- public class GalleryAdapter extends BaseAdapter {
- private LayoutInflater mInflater;
- private Context mContext;
- private int width;
- private int count;
- private int[] mImageIds;
- public GalleryAdapter(Context context, int[] ids) {
- mContext = context;
- mImageIds = ids;
- mInflater = LayoutInflater.from(mContext);
- DisplayMetrics dm = mContext.getApplicationContext().getResources()
- .getDisplayMetrics();
- width = dm.widthPixels;
- count = mImageIds.length;
- }
- @Override
- public int getCount() {
- return Integer.MAX_VALUE;//用于循环滚动
- }
- @Override
- public Object getItem(int position) {
- return position;
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- position = position % count;
- if (convertView == null) {
- convertView = mInflater.inflate(R.layout.gallery_item, null);
- }
- ImageView v = (ImageView) convertView.findViewById(R.id.img);
- v.setLayoutParams(new Gallery.LayoutParams(width, 200));
- v.setScaleType(ImageView.ScaleType.FIT_XY);
- v.setBackgroundResource(mImageIds[position]);
- return v;
- }
- }
转载于:https://blog.51cto.com/devinzhao/888666