Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to scale a layout with screen size

Consider this layout (pulled from here):

enter image description here

I'd like to understand the principles behind making this layout scale with screen size. For the square, a custom onMeasure function works nicely:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}

The width and height of the custom Togglebuttons and Imagebuttons below should scale to fill the remainder of the screen, minus layout_margins, and the text and images within should scale to fill the buttons, minus padding. The outer margin should also scale.

My first thought was to use a relative layout to position the buttons, and layout_margin/padding attributes to create margins. However, relative layouts and layout_margin/padding require fixed pixel values, so they aren't scalable.

I then thought of using nested linear layouts with layout_weights to position the buttons, and placeholder views to create margins. Although these techniques are scalable, they don't work with buttons, because buttons have many attributes (text size, image size, corner radius, etc.) that require fixed pixel values. This limitation means, for example, that the following xml:

<ToggleButton 
    android:layout_weight="1"
    style="@style/myButton"
    [...] />
<View 
    android:layout_weight="1"/>
<ImageButton 
    android:layout_weight="1"
    style="@style/myButton"
    [...] />

won't necessarily make the two buttons, and the space between them, all the same width. It all depends on the text size, image size, etc. etc. of the buttons.

I've taken a look at this question but I feel there should be a simpler solution for such a simple problem, that shouldn't require resorting to too much non-XML.

like image 614
1'' Avatar asked Dec 27 '22 12:12

1''


1 Answers

If you build your views using "dp" it would, basically, be the same size for eack screen size.
In most cases you will prefer that your view will resize itself proportional to the screen size.
Of course, in most cases you will need to build separate layouts for tablets.
But, besides I can recommend you to do the next steps:

1. Add this library to your project.

2. Now in your layout you can write views like that:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="I'm scalable!" 
    android:textSize="@dimen/_12sdp"/>

In this example your TextView will scale on each screen size.

3. Preview all screen sizes to see the result.

like image 121
Elhanan Mishraky Avatar answered Jan 12 '23 04:01

Elhanan Mishraky