I am trying to write code for zoom in/out the whole page/screen of the app. I was given this link
Android - zoom in/out RelativeLayout with spread/pinch
but it's really difficult for a beginner to understand all the procedures to follow.
If someone can help and provide clearer explanation on this topic, I and other beginners will surely appreciate it.
So far I have set MainActivity
, AnswerActivity
and Fragments
.
First, lets start simple. Scaling is relatively easy. (this code is not used in the further examples):
sx
andsy
is scale[X/Y]That is the fundamentals of scaling. Now we go to the hard part: Pinch zoom. this requires user input in the form of touch events.
Start by setting an onTouchListener if you cannot use onTouchEvent for the root view. (I will not show this part)
Before you even start, declare a float called scaleFactor:
First, we need a ScaleGestureListener. This can be a nested class if wanted:
Secondly we need the OnScaleGestureListener:
Now, this is where it splits in two. If possible, use
onTouchEvent(MotionEvent ev)
. If you cannot use this method(when you add@Override
above it it shows an error) you have to use onTouchListener instead. set it on the TextView(tv.setOnTouchListener(this);
. Make sure the class implements OnTouchListener)Now, whatever method you picked, MAKE SURE IT RETURNS
true
!This code should work in both methods, and it isn't limited to a specific method:
(ev is MotionEvent)
Now, the base code is in place. Now we need to create the instance for
s
:Globally declare:
and where you inflate the layout:
Now, assuming all the components are in place you have a functioning zoom-in/out system. Please note that this does not cover scrolling on the zoomed view. You have to create an offsetX/Y variable, and take input when there is one pointer and check how far a distance you want to move.
Using a TextView and touch events, you can use #setScrollX or #setScrollY along with an offset to set the new, scrolled position.
It may though be easier to create your own, custom text view. You do this by creating a new class and making it extend TextView. Then you put modifications as you want into there. This would allow you to add zoom and such into the custom TextView. This is though a prefered way to do it if you have multiple textviews in a single class or you have multiple activities with a zoomable and scrollable textview.
EDIT: Custom textview
Sadly, not a lot of the integrated tools does nto work.
android:scrollbars
on a textview doesn't work for an instance. So first the TextView has to have a ScrolLView around it:And ZoomableTextView:
You need this dependency first:
This is to get the AppCompat library so the TextView can use new features while maintaining support for earlier versions. now for the class: