Android: specify a resource if the width is less than that of a particular DP

How to use the resource qualifier system in Android to indicate that I want the resource to be applied only if the width is less than a certain value?

To develop, suppose I want to provide one layout when the current available width is up to 320dp, and another layout for all other cases. This is what comes to mind:

layout-w320dp/mylayout.xml
layout/mylayout.xml

However, according to my understanding of the resource matching algorithm , even a large device (say, a tablet in the landscape) qualifies as w320dp- because, well, the available width will be more than 320dp.

Thus, the resource from layout-w320dpwill always be selected - even for larger phones and tablets. The only time a default resource is selected from a folder layoutif the available width is less than 320 dp.

So, how can I express the less relationship using the Android resource mapping system?

+4
source share
2 answers

Ugh! Just after posting the question, I realized that one way to do this would be to negate the equation - i.e.:

layout-w320dp/mylayout.xml --> layout for screens larger than 320dp
layout/mylayout.xml  --> layout for up to 320dp

However, I am still interested in knowing whether the initial “less” relationship can be achieved, since it makes it much clearer.

+4
source
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = metrics.heightPixels / density;
float dpWidth  = metrics.widthPixels / density;

if(dpWidth >= 360){
    //change your resource      
}
-1
source

All Articles