I would like to design an application which could work with devices of any screen resolution.
My idea to do so was to create one Custom View for each type of View I use, and use the layout_width and layout_height specified in the XML as a percentage of the parent size (for example, layout_width="100dp" is equivalent to fill_parent, and layout_width="50dp" means the View‘s width will be half the parent’s one).
Here is the custom TextView class I made:
public class RSTextView extends TextView {
public RSTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int w, int h) {
int parentWidth = ((View)this.getParent()).getWidth();
int parentHeight = ((View)this.getParent()).getHeight();
Log.i(null, "Width: " + w + "; Height: " + parentHeight);
this.setMeasuredDimension(parentWidth * MeasureSpec.getSize(w) / 100,
parentHeight * MeasureSpec.getSize(h) / 100);
}
}
However, it does not work. The parentWidth and parentHeight size is always 0.
Is there any better way to create an application with a relative size?
And if it is the right way to go, how can I retrieve the View‘s parents’ size from the onMeasure method?
Since you’re checking a view’s height during the layout phase, you probably want to be using
getMeasuredHeight, notgetHeight, but I’m not sure you need to be doing what you’re doing at all. It’s hard to tell from your description, but it seems like you might be trying to recreate the behavior ofLinearLayoutweights. For example, if you have a horizontalLinearLayoutwith 3 children, you can easily set the first to take up half its width and the others each to take up 25% by assigning them0pxlayout_widths andlayout_weights of 2, 1 and 1 respectively (or any other weights of those proportions).If you do decide to go the custom
Viewroute, though, don’t overload whatlayout_heightandlayout_widthdo — use custom XML attributes to take the argument for the percentages (I’d dig intoLinearLayout‘s code to see howlayout_weightis implemented).