I’m trying to understand Android’s View structure and I’m a little confused on how to position child views
Let’s say I have a FrameLayout that will contain my custom view. My custom view only draws a rectangle 50×50 px.
So I set my View.setMeasureDimension(50, 50);
Now how should I move this view? I found a couple of ways of doing it.
1: I could do something like canvas.drawRect(new Rect(offsetX, offsetY, right, bottom)); but this will make my View larger and thereby my measureWidth / height are not valid any longer?
2: Set padding on the parent element, and thereby affect the left / top View.getLeft() / View.getTop(). But this will affect all child elements.
3: Use View.offsetLeftAndRight( number of pixels to move ). I do not quite understand what this actually does. Does it cause some kind of canvas.translate() ? But this way I need to keep the state on how many times I called offsetLeftANdRight() because calling offsetLeftANdRight(10) and then offsetLeftANdRight(10) will move it 20px.
I’m a bit confused on what way is the “correct” way of doing it. Is there a better way?
Android apps run on devices of different sizes, with often completely different screens. Because of that you shouldn’t be using any absolute positioning or sizing. Wherever possible create views and position them relative to each other.
You need to become familiar with the various views Android provides to create layouts:
http://developer.android.com/guide/topics/ui/layout-objects.html
It sometimes takes a lot of thought as items will be positioned differently on different devices (and orientations) so the view relationships are more important than absolute positions.
LinearLayout is a good all-purpose container for placing controls, though RelativeLayout is often more efficient (if a bit harder to use sometimes)
Once items are positioned relative to each other you can use padding and margins to tweak their positions.