Search code examples
androidlocaleandroid-drawable

How to access locale qualified drawable in android


I tried to make separate drawable for different locale e.g. french_flag, german_flag, etc. What i did was, in the android studio project structure i made a folder with "drawable-<qualifier>" format so it's like drawable-fr, drawable-de. After that i put the specific flag image png. I also put usa_flag.png in the main drawable folder as default locale.

When i load usa_flag.png by accessing it with R.drawable.usa_flag, it worked fine. But when i tried to access the R.drawable.french_flag it always throws unsolved reference on compile time.

I searched in google and it says I can't access qualified drawable resources directly through R.drawable.xxxx, i need to use context.resources.getDrawable(R.drawable.xxx) but this method also doesn't works and threw out the same error.

I also used context.resources.getIdentifier("french_flag", "drawable", context.packageName), this helped me get through the unsolved reference compile time error, but when I change the locale inside my app using Locale.setDefault(), it throws similar error : android.content.res.Resources$NotFoundException: Resource ID #0x0


Solution

  • If I understood correctly your question, in order to solve the issue you have to make sure that the drawable has the same file name on each drawable- folder.

    For instance, when talking about flags, all the drawable folders such as drawable-fr, drawable-es, etc has the same flag.png (or svg) picture and from the code you access the flag with context.resources.getDrawable(R.drawable.flag).

    Once you change the locale from the phone's settings then the app will automatically pick the correct flag.