How can I put utf-16 characters in Android string resource?

14,864

Solution 1

But the strings.xml resource file is UTF8

If it's UTF-8 encoded, you can put your emojis directly. But then you risk that your editor or another piece of software destroys them.

If you are putting them in XML, you can try using XML entities: 😀, I'm not sure how well Android supports them though.

You can also use surrogate pairs: convert the emoji to UTF-16 and use standard \u escape. You can for example check out this page, it even tells you how to create a string litaral in Java: http://www.fileformat.info/info/unicode/char/1F600/index.htm

😜 → U+1F600 → "\uD83D\uDE00"

Solution 2

The easiest way it just copying and pasting the emoji, it works from Android Studio 3.0 and newer

Share:
14,864

Related videos on Youtube

Shoham
Author by

Shoham

Updated on June 04, 2022

Comments

  • Shoham
    Shoham almost 2 years

    I want to use Emojis in my app's strings. All strings reside, of course, in strings.xml

    The problem is that not all Emojis are 16 bit friendly. Some Emojis can be represented as "normal" 16 bit hex: '\u26FF' but some are 32 bit hexes (UTF-16), usually represented as: '\x1F600'. I have no problem dealing with those inside the app, in code. But the strings.xml resource file is UTF8 encoded, and does not deal properly with non 16 bit escape chars.

    I tried using '\x1F600' - because I saw that '\u26FF' works just fine. But it seems not to devour the 'x' escape char. Nor did it like the regexp notation '\x{1F600}'

    So I ended up using a string placeholder '%1$s' and filling in the Emoji in code like this:

    // greeting_3 is defined as: "hello there %1$s!"
    String s = context.getString(R.string.greeting_3, "😜");
    // OR:
    String s = context.getString(R.string.greeting_3, new String(Character.toChars(0x1F61C)));
    

    This is not a very elegant solution... is there a proper way to put 32 bit UTF-8 chars in strings.xml ?

  • Shoham
    Shoham almost 10 years
    I tried the direct way, but it causes my application to segfault. This is why I started looking for alternatives :-) I will try out the other options.
  • Mihai Nita
    Mihai Nita almost 10 years
    I have tried the raw text and 😀 with segfault at runtime, and �� with build error ("Error in an XML file: aborting build. "). I think you can safely file a bug, it's valid.
  • Ernest Poletaev
    Ernest Poletaev about 8 years
    This crashed on Samsung S4 5.0.1
  • Mr-IDE
    Mr-IDE almost 7 years
    Example Java code: String grinningFaceEmoji = "\uD83D\uDE00";
  • friedger
    friedger about 6 years
    <U+1F642> is not valid in the resource file
  • Vlad
    Vlad over 3 years