I am trying to get swipe up and swipe down gestures working in Fragment. The same is working fine with activity. In Fragment, I have an issue with dispatchTouchEvent. How d
You must dispatchTouchEvent in your parent activity like that Add this code to parent activity:
private List<MyOnTouchListener> onTouchListeners;
@Override
protected void onCreate(Bundle savedInstanceState) {
if(onTouchListeners==null)
{
onTouchListeners=new ArrayList<>();
}
}
public void registerMyOnTouchListener(MyOnTouchListener listener){
onTouchListeners.add(listener);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
for(MyOnTouchListener listener:onTouchListeners)
listener.onTouch(ev);
return super.dispatchTouchEvent(ev);
}
public interface MyOnTouchListener {
public void onTouch(MotionEvent ev);
}
OnSwipeTouchListener:
public class OnSwipeTouchListener{
private final GestureDetector gestureDetector;
public OnSwipeTouchListener (Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
private final class GestureListener extends SimpleOnGestureListener {
//override touch methode like ondown ...
//and call the impelinfragment()
}
public void impelinfragment(){
//this method impelment in fragment
}
//by calling this mehod pass touch to detector
public void onTouch( MotionEvent event) {
gestureDetector.onTouchEvent(event);
}
And add this code to fragment you like to dispach touch in it:
//ontouch listenr
MainActivity.MyOnTouchListener onTouchListener;
private OnSwipeTouchListener touchListener=new OnSwipeTouchListener(getActivity()) {
public void impelinfragment(){
//do what you want:D
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setting for on touch listener
((MainActivity)getActivity()).registerMyOnTouchListener(new MainActivity.MyOnTouchListener() {
@Override
public void onTouch(MotionEvent ev) {
LocalUtil.showToast("i got it ");
touchListener.onTouch(ev);
}
});
}
I use this method to get all swipe to right or left event in fragment without conflicting with other elem in page .unlike rax answer
If your goal is to detect/handle swipe, add touch event listener on the fragment's view after creating the view.
Fragments are attached to activity, not replacing activity. So you can still override dispatchTouchEvent in your fragment parent activity and pass any actions from there.
For example:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("MY_FRAGMENT_TAG");
myFragment.doSomething();
return super.dispatchTouchEvent(ev);
}