I have a problem with placing my views (my class extends View
) in a specific location.
I have designed a game that treats the screen as a net of grids. I get from the user x and y coordinates of a specific view (I have different types of views).
My first mission is to set the correct view in its place. How can I do it?
I am using RelativeLayout
for the screen.
P.S. I don't want to use AbsoluteLayout
params because it was truncated.
Suppose u want to place a button on a screen and u have 100x60 cells in ur grid. That is u have divided the screen into 100x60 cells, by considering number of pixels along horizontal and vertical. In landscape mode, the number of width pixels will be more so hence consider dividing it by 100, and the number of height pixels will be less so divide it by 60. So considering that ur using a TAB having resolution 800x480 pixels, In landscape mode - u have 8 pixels(800/100) per cell along horizontal and 8 pixels(480/60) per cell along vertical.The division factor will be vice-versa in portrait mode.
Now u want to place a button of width say 35 cells and height is wrap_content according to the text on it and place it on co-ordinates 20,20(x,y) cell number. I have provided a method to achieve this..And note: What ever view u will place in this fashion or using this idea, it will be in same place and have same dimensions and look and feel on multiple display resolution.[here pixels_grid_X = pixels per cell along horizontal(800/100)] [Similiarly pixels_grid_Y = pixels per cell along vertical(480/60)]
Method for placing a button
This is not the best way to achieve it, but it's a solution...
Create a class that extends your parent
ViewGroup
, sayRelativeLayout
or some otherViewGroup
s. Find your own view in overridingonFinishInflate()
.Override the
onLayout()
method and manually layout your own view after callingsuper.onLayout()
.Finally, every time you want to refresh the location of your own view, just call
requestLayout()
.Here is a sample below:
But this is not an efficient solution.
If you are making games, try
SurfaceView
or evenGLSurfaceView
and draw the objects by your own withCanvas
.