本文主要介紹如何使用gallery隻滑動一頁以及其實作原理。
效果圖如下:

1、引入公共庫
2、使用
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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_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();
}
public void onnothingselected(adapterview<?> parent) {
});
不過這個函數性能很差,即便隻是textview.settext也會明顯示卡頓.
3、原理
18
19
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)) {
// 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處理。