Relationship between Rect class and View

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

Awkwardly! :grin:

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.

What about height /width ? I am guessing for l/r/t/b , i could use ,view.left=l , view.right=r ,…etc

Use LayoutParams (the Java/Kotlin equivalent of android:layout_ attributes like android:layout_height and android:layout_width).

thanks it worked!. I wonder if it is safe for production though. would it sustain orientation changes and other lifecycle stuff ?

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.

1 Like