Home > Enterprise >  Resource Qualifiers - determine currently selected programatically?
Resource Qualifiers - determine currently selected programatically?

Time:01-05

I'm currently working on support for multiple screen sizes for my app, and stumbled upon this advice from google; https://developer.android.com/guide/topics/large-screens/support-different-screen-sizes#kotlin

It has this code;

private fun computeWindowSizeClasses() {
    val metrics = WindowMetricsCalculator.getOrCreate()
        .computeCurrentWindowMetrics(this)

    val widthDp = metrics.bounds.width() /
        resources.displayMetrics.density
    val widthWindowSizeClass = when {
        widthDp < 600f -> WindowSizeClass.COMPACT
        widthDp < 840f -> WindowSizeClass.MEDIUM
        else -> WindowSizeClass.EXPANDED
    }

    val heightDp = metrics.bounds.height() /
        resources.displayMetrics.density
    val heightWindowSizeClass = when {
        heightDp < 480f -> WindowSizeClass.COMPACT
        heightDp < 900f -> WindowSizeClass.MEDIUM
        else -> WindowSizeClass.EXPANDED
    }

    // Use widthWindowSizeClass and heightWindowSizeClass
}

Then there are the in-project resource qualifiers, eg

/layout 
/layout-w600dp
/layout-w840dp

When Android chooses a layout based on width, does it use this exact same calculation?

widthDp = metrics.bounds.width() / resources.displayMetrics.density

Different layouts will have different elements. How do I ensure my class code is expecting the same layout that Android has chosen?

CodePudding user response:

If you really need to know, you can have a values resource for each resource qualifier you are supporting. For example,

values/whatever.xml:

<string name="resource_qualifier">default</string>

values-w600dp/whatever.xml:

<string name="resource_qualifier">w600dp</string>

And then you can getString() this resource value.

  •  Tags:  
  • Related