The
TextView
has an
OnTouchListener
that detects a touch.
But we want to detect more than a touch.
We want to detect a fling,
which consists of a series of touches in different places.
(“Fling” is the Android word for “swipe”.)
Each time the
onTouch
method of the
OnTouchListener
receives a
MotionEvent
,
it passes the
MotionEvent
to a
GestureDetector
.
After the
GestureDetector
receives enough of these
MotionEvent
s,
the
GestureDetector
can conclude that the
MotionEvent
s
constitute a swipe.
The
GestureDetector
then calls the
onFling
method of the
SimpleOnGestureListener
that was plugged into the
GestureDetector
.
The object plugged into the
GestureDetector
must be an
OnGestureListener
.
But
OnGestureListener
is an interface,
and to create an object that implements this interface
we would have to override all six of the interface’s abstract methods.
If we are interested in overriding only one of them (in our case,
onFling
),
it’s easier to subclass
SimpleOnGestureListener
,
which provides six overriding methods that do nothing.
We only have to override the methods that interest us.
MainActivity.java
activity_main.xml
strings.xml
AndroidManifest.xml
build.gradle
(Module: app).
Math.atan2
gets the angle in which the fling is pointing
(with the
y
value negated because the Android Y axis points downwards),
and
Math.toDegrees
converts it from radians to degrees.
Only the
TextView
is touch-sensitive,
so we expand it to fill the entire screen by giving it a
layout_width
and
layout_height
of
fill_parent
in
activity_main.xml
.
To center the text in the
TextView
,
the
TextView
has
android:gravity="center"
.
When a fling is detected, we change the gravity to
TOP
.
getPressure
and
getSize
return meaningful, or at least serious looking, values on my
Motorola MB612 phone.
On my
Azpen
A272 tablet,
the pressure is always 1 and the size is always .0392157
(close to the reciprocal of 25.5).
On my Amazon Fire HD 6 tablet,
the pressure might be meaningful and the size is always zero.
On the Nexus 5X emulator,
the size is microscopic and the pressure is always .503906.
For portability,
I wrote the special characters as Unicode code numbers
(\u
followed by four hexadecimal digits)
rather than as the characters themselves.
Here are links to the code charts:
\u00B0 |
° | degree |
\u2019 |
’ | apostrophe |
\u0027 |
' | single quote |
\u2190 |
← | left arrow |
\u2191 |
↑ | up arrow |
\u2192 |
→ | right arrow |
\u2193 |
↓ | down arrow |
\u2196 |
↖ | upper left arrow |
\u2197 |
↗ | upper right arrow |
\u2198 |
↘ | lower right arrow |
\u2199 |
↙ | lower left arrow |