Is it possible to create a clone/wrapper of Context, having a different locale set for it than the original?

39 Views Asked by At

Background

I'm trying to avoid wrong formatting issues on various usages of Context, so that numbers will be set like on English instead of Arabic and others.

The problem

One simple example of a function that doesn't let me set the locale myself is formatShortFileSize, and just uses Context:

fun getHeapMemStats(context: Context): String {
    val runtime = Runtime.getRuntime()
    val maxMemInBytes = runtime.maxMemory()
    val availableMemInBytes = maxMemInBytes - (runtime.totalMemory() - runtime.freeMemory())
    val usedMemInBytes = maxMemInBytes - availableMemInBytes
    val usedMemInPercentage = usedMemInBytes * 100 / maxMemInBytes
    return "used: " + Formatter.formatShortFileSize(context, usedMemInBytes) + " / " +
            Formatter.formatShortFileSize(context, maxMemInBytes) + " (" + usedMemInPercentage + "%)"
}

What I've tried

At first I thought I should use a customized ContextWrapper, but it didn't seem like it could be useful.

Then I tried to use createConfigurationContext, and then copy the configuration and setting a locale for it:

Log.d("AppLog", "getHeapMemStats:${getHeapMemStats(this)}")
val newConfiguration=Configuration(resources.configuration)
newConfiguration.setLocale(Locale.ENGLISH)
val newContext=  createConfigurationContext(newConfiguration)
Log.d("AppLog", "getHeapMemStats2:${getHeapMemStats(newContext)}")
Log.d("AppLog", "getHeapMemStats3:${getHeapMemStats(this)}")

This works only partially, as the "MB" is written fine, but not the actual digits:

getHeapMemStats:used: ٥٫٠ ميغابايت / ٢٦٨ ميغابايت (1%)
getHeapMemStats2:used: ٥٫٠ MB / ٢٦٨ MB (1%)
getHeapMemStats3:used: ٥٫١ ميغابايت / ٢٦٨ ميغابايت (1%)

The question

How come only the units get localized according to what I've set, and not the digits?

How can I make the Context/resources to be set to a locale of my choice, that not just the words will be set according to it, but also the digits?

0

There are 0 best solutions below