在开发中经常会用到对于fragment滑动的判断,比如右滑返回,写一个abstract的父类放在代码库中,可以减少代码量。
定义:
public abstract class ListenSlideFragment extends Fragment implements OnTouchListener
一些变量
protected float touchStartX = 0;
protected float touchStartY = 0;
protected float touchStopX = 0;
protected float touchStopY = 0;
protected float horizontalSlideDistance = 0;
protected float verticalSlideDistance = 0;
protected float horizontalSlideBench = 200;
protected float verticalSlideBench = 200;
有时候基准值需要自定义
public void setHorizontalSlideBench(float horizontalSlideBench)
{
this.horizontalSlideBench = horizontalSlideBench;
}
public void setVerticalSlideBench(float verticalSlideBench)
{
this.verticalSlideBench = verticalSlideBench;
}
代表滑动方向的静态变量
public static final int LEFT_SLIDE = 0;
public static final int RIGHT_SLIDE = 1;
public static final int UP_SLIDE = 2;
public static final int DOWN_SLIDE = 3;
重写onTouch事件,返回值要写成false。
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStartX = event.getX();
touchStartY = event.getY();
break;
case MotionEvent.ACTION_UP:
touchStopX = event.getX();
horizontalSlideDistance = touchStartX - touchStopX;
touchStopY = event.getY();
verticalSlideDistance = touchStartY - touchStopY;
if (horizontalSlideDistance > horizontalSlideBench)
{
passSlideEvent(LEFT_SLIDE);
}
else if (horizontalSlideDistance < (-horizontalSlideBench))
{
passSlideEvent(RIGHT_SLIDE);
}
if (verticalSlideDistance > verticalSlideBench) {
passSlideEvent(UP_SLIDE);
}
else if (verticalSlideDistance < (-verticalSlideBench))
{
passSlideEvent(DOWN_SLIDE);
}
break;
default:
break;
}
return true;
}
输出信息
public void outLog(String message) {
Log.i(getFragmentTag(), message);
}
以下是需要重写的两个方法:
传递滑动事件,这个方法要在子类中具体重写
获取fragment的TAG,用于LOG
public abstract void passSlideEvent(int slideCode);
public abstract String getFragmentTag();
使用
继承ListenSlideFragment
public class CenterFrag extends ListenSlideFragment
重写方法:
@Override
public void passSlideEvent(int slideCode) {
switch (slideCode) {
case UP_SLIDE:
outLog("上滑");
break;
case DOWN_SLIDE:
outLog("下滑");
break;
case LEFT_SLIDE:
outLog("左滑");
break;
case RIGHT_SLIDE:
outLog("右滑");
break;
default:
break;
}
}
在加载fragment之前要设置为activity的listener:
findViewById(R.id.container).setOnTouchListener(centerFrag)
fragmentTransaction.add(R.id.container, centerFrag)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()