Reputation:
I have an activity. This activity has a two layout: for wide screen and for small screen. I have to init fields in my activity depends on used layout. For example:
class MyActivity extends Activity {
private int i; //is_layout1? i = 10 : i = 11;
}
How to do it? I would like to avoid if
to do it.
How to?
Upvotes: 0
Views: 59
Reputation: 1005
There are multiple ways to achieve this. You can check screen size and density per-pixel and resize all the element you have according to that dynamically. But this approach is depended on much code Java code and it is not a clean way to design your layout.
The better way is to create separate layout for different size according to screen size type and in runtime it will be decided by the compiler which file needs to be used according to screen size it is running on.
In this way, you have to use layout folder names like this....
layout
activiy_main.xml
layout-large
activiy_main.xml
layout-small
activiy_main.xml
layout-xlarge
activiy_main.xml
You can also use one layout file but multiple folder for values folder according to screen size and dp which contains dimens.xml file. This file will contain different values of element size for different screen size.
In this way, you should have folder in res directory like this....
layout
activity_main.xml
values
dimens.xml
values-hdpi
dimens.xml
values-mdpi
dimens.xml
values-xhdpi
dimens.xml
here you may have a button's margin value 20dp for hdpi folder and 30dp for xhdpi folder.
If any variable needs to be initialized according to screen size, you can use separate integers.xml file for different values folder and put values according to your need. https://developer.android.com/guide/topics/resources/more-resources.html#Integer
Upvotes: 1