Question

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?

Was it helpful?

Solution

Since you're checking a view's height during the layout phase, you probably want to be using getMeasuredHeight, not getHeight, 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 of LinearLayout weights. For example, if you have a horizontal LinearLayout with 3 children, you can easily set the first to take up half its width and the others each to take up 25% by assigning them 0px layout_widths and layout_weights of 2, 1 and 1 respectively (or any other weights of those proportions).

If you do decide to go the custom View route, though, don't overload what layout_height and layout_width do -- use custom XML attributes to take the argument for the percentages (I'd dig into LinearLayout's code to see how layout_weight is implemented).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top