现在的位置: 首页 > 综合 > 正文

Android Gallery setSelection()和onFling()方法的区别

2018年08月02日 ⁄ 综合 ⁄ 共 2057字 ⁄ 字号 评论关闭

由于对gallery有个将元素居底的需求,我们的实现方法就是将Gallery在布局中设置android:layout_alignParentBottom="true";可是光光有这个没有用,因为Gallery的默认方式是将元素居中的,并且居中这个方法在源码中的private的,无法重写的。所以这里只能绕个弯,将Gallery的高度设置成包裹图片的高度,这样在galleryAdapter中我们就要实时的去取图片的高度,这样一来的确实现了对gallery有个将元素居底的需求。

不过,对gallery还有个需求就是要支持自动轮播和滑动。没想到这里出了个问题。在自动轮播我们是使用setSelection()这个方法,这个方法对不同高度的图片显示没有问题,但是滑动了就不行了。查看了源代码才发现,setSelection()这个方法里有实现requestLayout和invalidate方法,而滑动就没有实现这2个方法。看来就是这个原因了。然后查了下这两个方法。

requestLayout:当view确定自身已经不再适合现有的区域时,该view本身调用这个方法要求parent view重新调用他的onMeasure onLayout来对重新设置自己位置。
特别的当view的layoutparameter发生改变,并且它的值还没能应用到view上,这时候适合调用这个方法。
invalidate:View本身调用迫使view重画。

所以对Gallery源码中在onTouchEvent()方法中设置的时候将这个方法加进去就好了。

package com.geekpark.utils;

import android.content.Context;
import android.graphics.Camera;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;

public class CustomGallery extends Gallery {

    public CustomGallery(Context context) {
        super(context);
    }

    public CustomGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        int position = getSelectedItemPosition()%getChildCount();
        int kEvent;
        if (isScrollingLeft(e1, e2)) {
            // Check if scrolling left
            kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            // Otherwise scrolling right
            kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        return onKeyDown(kEvent, null);
//         return true;
    }
    
    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
        return e2.getX() > e1.getX();
    }

    protected boolean getChildStaticTransformation(View child, Transformation t) {

        return super.getChildStaticTransformation(child, t);

    }

    public boolean onTouchEvent(MotionEvent event) {

        boolean result;
        if(event.getAction() == MotionEvent.ACTION_UP){
            requestLayout();
            invalidate();  
        }
    
        try {
            result = super.onTouchEvent(event);
        } catch (NullPointerException e) {
            result = false;
        } catch (OutOfMemoryError ex) {
            ex.printStackTrace();
            result = false;
            System.gc();
            System.gc();
        }
        return result;
    }

}

抱歉!评论已关闭.