Relationship between Rect class and View
from the CommonsWare Community archivesAt October 18, 2020, 3:49pm, root-ansh asked:
Given some rectangular points on screen, can we put a view there? (or move some invisible view to that place and make it visible?) What would be the relation between the height/width/margin of that view and the rectangular coordinates?
Here’s a cropper library which is giving me the rectangular coordinates of the screen from where the image was cropped. How can I show an overlaying view on these points? The image shows how cropper is working
Here are some logs , provided by the cropper :
2020-10-18 21:06:50.254 E/TAG: OVERLAY RECTANGLE DETAILS:
2020-10-18 21:06:50.255 E/RECT>>: logRectangle: rect =Rect(297, 1091 - 2673, 4752)
2020-10-18 21:06:50.255 E/RECT>>: logRectangle: left,right,top,bottom =297,2673,1091 , 4752
2020-10-18 21:06:50.255 E/RECT>>: logRectangle: center x,y =1485.0, 2921.5
2020-10-18 21:06:50.255 E/RECT>>: logRectangle: rect width,height =2376, 3661
At October 18, 2020, 4:07pm, mmurphy replied:
Awkwardly!
More seriously, I haven’t had to do this sort of thing in years. AFAIK, the “best practice” options are either:
- Create a custom
ViewGroup
that knows how to position and size something at your desired location, or - Use a
FrameLayout
, with margins to control the position of your view
You can probably find a copy of the long-since-deprecated AbsoluteLayout
floating around somewhere, which may give you ideas for the former.
Just please only do this for coordinates obtained at runtime (e.g., via touch input). The reason why AbsoluteLayout
was deprecated was that it led developers to try using absolute coordinates for positioning widgets, which works poorly across screen sizes and gives the app a lovely “early 1990’s Visual Basic” sort of vibe.
At October 18, 2020, 5:04pm, root-ansh replied:
What about height /width ? I am guessing for l/r/t/b , i could use ,view.left=l , view.right=r ,…etc
At October 18, 2020, 5:17pm, mmurphy replied:
Use LayoutParams
(the Java/Kotlin equivalent of android:layout_
attributes like android:layout_height
and android:layout_width
).
At October 19, 2020, 4:13am, root-ansh replied:
thanks it worked!. I wonder if it is safe for production though. would it sustain orientation changes and other lifecycle stuff ?
At October 19, 2020, 10:31am, mmurphy replied:
It will not work directly after an orientation change. Not only would you need to recreate this view programmatically (as with other types of configuration changes), but the coordinates may no longer be correct due to the change in screen geometry.