This article introduces you to the touch event implementation of monitoring Fragment. If you have a better mechanism, you can leave a message to communicate. Let’s take a look at the detailed introduction below:
Everyone knows that there areonTouchEvent
Method, can be used to implement monitoring of touch events.
Touch events of activity
@Override public boolean onTouchEvent(MotionEvent event) { return (event); }
But forFragment
, but there is no such method, if we are infragment
How to implement it if you want to monitor touch events?
My method is to implement the distribution of touch events by myself.
Define an interface first
public interface MyOnTouchListener { public boolean onTouch(MotionEvent ev); }
Have another onelist
storagelistener
private ArrayList<MyOnTouchListener> onTouchListeners = new ArrayList<MyOnTouchListener>( 10);
Then register, destroy and distribute yourself
fragment
Touch event distribution, distribute touch events to each responsivefragment
@Override public boolean dispatchTouchEvent(MotionEvent ev) { for (MyOnTouchListener listener : onTouchListeners) { if(listener != null) { (ev); } } return (ev); } public void registerMyOnTouchListener(MyOnTouchListener myOnTouchListener) { (myOnTouchListener); } public void unregisterMyOnTouchListener(MyOnTouchListener myOnTouchListener) { (myOnTouchListener) ; }
Then infragment
We can use it like this: initialize the listener, and thenactivity
Register and monitor gestures in the monitor at the same time.
onTouchListener = new () { @Override public boolean onTouch(MotionEvent ev) { (ev); return false; } }; ((MusicActivity) getActivity()).registerMyOnTouchListener(onTouchListener);
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.