问题
Is there a way to know exactly which layout (and other resources) are chosen by Android during runtime based on screen density and size when supporting multiple screens?
I need to know the folder's name.
EDIT:
I need to know the folder's name programmatically.
回答1:
If you're just doing this for debugging purposes, I'd recommend doing something like this: For each qualifier that you have a layout/drawable for, have a values folder with the same qualifier (e.g. if you have a layout-hdpi, also have a values-hdpi to match). Add a strings.xml for each of these folders, and define a string:
In values-hdpi
:
<string name="folder_name">hdpi</string>
In values-xhdpi
:
<string name="folder_name">xhdpi</string>
Then just resolve the string when you need it, and it will tell you which folder was selected.
回答2:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi){
case DisplayMetrics.DENSITY_LOW:
break;
case DisplayMetrics.DENSITY_MEDIUM:
break;
case DisplayMetrics.DENSITY_HIGH:
break;
case DisplayMetrics.DENSITY_XHIGH:
break;
case DisplayMetrics.DENSITY_XXHIGH:
break;
case DisplayMetrics.DENSITY_XXXHIGH:
break;
}
回答3:
Imagine you have a structure like this:
res/
drawable-mdpi/image.png
drawable-hdpi/image.png
drawable-xhdpi/image.png
layout/main.xml
layout-land/main.xml
layout-xlarge/main.xml
layout-sw600dp/main.xml
and you want to know, which layout is used.
One way would be to put a value in resources:
res/
values-mdpi/strange_info.xml with:
<string name="image_is_from_folder">drawable-mdpi</string>
values-hdpi/strange_info.xml with:
<string name="image_is_from_folder">drawable-hdpi</string>
values-xhdpi/strange_info.xml with:
<string name="image_is_from_folder">drawable-xhdpi</string>
values/strange_info.xml with:
<string name="main_is_from_folder">layout</string>
values-land/strange_info.xml with:
<string name="main_is_from_folder">layout-land</string>
values-xlarge/strange_info.xml with:
<string name="main_is_from_folder">layout-xlarge</string>
values-sw600dp/strange_info.xml with:
<string name="main_is_from_folder">layout-sw600dp</string>
In code you just do
String mainFolderName = context.getResources().getString(R.string.main_is_from_folder);
I have some doubts regarding -Xdpi qualifier, but it should work (not tested). Note that with the above structure you will get "drawable-hdpi" on ldpi devices for image.png.
回答4:
The layout is chosen based on how you program it. Same with the menu and values. The photos are based on the definition: HDPI = High definition, LDPI = Low definition ect.
来源:https://stackoverflow.com/questions/17157220/easiest-way-to-know-programmatically-which-resources-folder-is-used-based-on-s