auto scroll a Gallery widget

ぐ巨炮叔叔 提交于 2019-12-05 06:11:31

So, it turns out that the original logic I had does work. A custom gallery implementing that logic but stripped of everything else in my class (below) works as expected, so it must be something else in my class that is causing this problem.

Thanks for your help HighFlyer :)

At the very least I learned about reflection... which is a very cool feature of Java.

public class CustomGallery extends Gallery {

    private Handler handler;

    public CustomGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        handler = new Handler();
        postDelayedScrollNext();
    }

    private void postDelayedScrollNext() {
        handler.postDelayed(new Runnable() {
            public void run() {
                postDelayedScrollNext();
                Log.d("CustomGallery", "dpad RIGHT");
                onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
            }
        }, 1000);
    }

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
        return e2.getX() > e1.getX();
    }

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        int kEvent;
        if (isScrollingLeft(e1, e2)) {
            Log.d("CustomGallery", "fling LEFT");
            kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            Log.d("CustomGallery", "fling LEFT");
            kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }
        onKeyDown(kEvent, null);
        return true;
    }

Note for future visitors: a better solution in situations like this (full-view gallery) is to use a ViewPager. It works like a gallery, but properly implements a setCurrentItem() method for smooth scrolling. With the compatibility package, it works for API 4 (Android 1.6!) and up, so everyone can use it.

It seems like you call onKeyDown method of your activity, not gallery. Try call

gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null)

instead. Correct me if I'm wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!