本文主要介绍如何使用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处理。