scompt.com scompt.com - 1 month ago 13
Android Question

Use alternative layout when there's not enough space

I have a

RelativeLayout
that has a number of controls in it. On some screens, there might not be enough room for this layout as well as the other screen elements. In this case, I'd like to use an alternate layout that excludes some controls and has less padding.

How can I implement this in a performant manner? The smaller layout should only be loaded if the larger layout definitely won't fit. I don't want to use the various screen size qualifiers because whether the layout will fit is a function of the width and height of the screen and the additional visible controls and that seems like it will get too complicated.

Answer

Personally I think you should use the new screen size qualifiers. It's how Android is designed and I think you should follow those rules.

But the only way I think to "hardcode" it would be something like this.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

or if you're targeting a lower API level:

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

then do something like this:

if(width < value_x_small && height < value_y_small){
        setContentView(R.layout.main_small);

} else if(width > value_x_small && height > value_y_small){
        setContentView(R.layout.main_large);

} else {
        setContentView(R.layout.main_larged);

}

This code allows you to select your own resources depending on the screen size in px. It's not the best way, you should also do a check on the dpi and screen rotation using for example:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

Rolf

Comments