Easiest way to know (programmatically) which resources folder is used based on screen density/size

妖精的绣舞 提交于 2019-11-30 14:07:06

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.

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;
            }

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!