原文摘自:http://www.apkbus.com/android-78656-1-1.html
以下操作步骤将帮助大家在使用FragmentActivity时使Fragment能触发到滑动事件:
1、在主activity(如MainContainerActivity)中设置一个接口(直接添加如下方法):
private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>(
10);
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
for (MyOnTouchListener listener : onTouchListeners) {
listener.onTouch(ev);
}
return super.dispatchTouchEvent(ev);
}
public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
onTouchListeners.add(myOnTouchListener);
}
public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) {
onTouchListeners.remove(myOnTouchListener);
}
public interface MyOnTouchListener {
public boolean onTouch(MotionEvent ev);
}
2、使Fragment实现OnGestureListener接口并实现onFling方法,定义一个手势对象private GestureDetector detector,绑定该对象到Fragment,在Fragment的onCreateView中实例化主activity的接口即可实现调用Fragment的onFling方法。
Fragment中具体代码如下:
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
public class ScanDetailsEditFragment extends MyFragment implements
TabContentFactory, OnGestureListener {
// 滑动手势
private GestureDetector detector;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//to-do
final GestureDetector mGestureDetector = new GestureDetector(
getActivity(), this);
MainContainerActivity.MyOnTouchListener myOnTouchListener = new MainContainerActivity.MyOnTouchListener() {
@Override
public boolean onTouch(MotionEvent ev) {
boolean result = mGestureDetector.onTouchEvent(ev);
return result;
}
};
((MainContainerActivity) getActivity())
.registerMyOnTouchListener(myOnTouchListener);
return view;
}
public void flingLeft() {//自定义方法:处理向左滑动事件
}
public void flingRight() {//自定义方法:处理向右滑动事件
}
@Override
public boolean onDown(MotionEvent arg0) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (e1.getX() - e2.getX() < -89) {
flingLeft();
return true;
} else if (e1.getX() - e2.getX() > 89) {
flingRight();
return true;
}
} catch (Exception e) {
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
}