06/20
2013

Gallery滑动一页(一个Item)效果

本文主要介绍如何使用Gallery只滑动一页以及其实现原理

Demo APK 可以方便的查看效果,在各大应用商店搜索 trinea android 下载即可,如:Google Play

可运行代码地址可见SlideOnePageGalleryDemo

 

效果图如下:

    

之前介绍过使用viewpager实现画廊(一屏多个Fragment)效果,两者各有优劣。Gallery滑动一页完成的处理事件会造成明显卡顿,但滑动过程中比ViewPager流畅。

 

1、引入公共库

引入TrineaAndroidCommon@Github(欢迎star和fork^_^)作为你项目的library(如何拉取代码及添加公共库),或是自己抽取其中的SlideOnePageGallery使用。

 

2、使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <cn.trinea.android.common.view.SlideOnePageGallery
        android:id="@+id/app_app_image_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:paddingBottom="@dimen/dp_40"
        android:spacing="4dp" />

    <include layout="@layout/trinea_info" />

</RelativeLayout>

用现在的cn.trinea.android.common.view.SlideOnePageGallery替换原来的Gallery即可.

 

如果需要设置没一页滑动后的操作,如修改指示器,可以调用setOnItemSelectedListener,如下:

imageGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		// Toast.makeText(context, Integer.toString(position), Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}
});

不过这个函数性能很差,即便只是TextView.setText也会明显卡顿.

 

3、原理
通过查看SlideOnePageGallery源码,我们可以发现,核心代码如下:

    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 kEvent;
        if (isScrollingLeft(e1, e2)) {
            // Check if scrolling left
            kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
        } else {
            // Otherwise scrolling right
            kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
        }

        onKeyDown(kEvent, null);
        return true;
    }

即重写gallery的onFling方法,将滑动事件转化为方向键事件,而Gallery的方向键事件就是滑动一页。左滑就当作KEYCODE_DPAD_LEFT处理,右滑就当作KEYCODE_DPAD_RIGHT处理。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

6 thoughts on “Gallery滑动一页(一个Item)效果