Display emoji from byte[], encoded using UTF-8

Example show how to display emoji on TextView, encoded from byte[].


To convert byte array to String using charset of UTF-8, we can call the constructor of String:
new String(bytes, "UTF-8")

Example:
package com.example.androidemoji;

import java.io.UnsupportedEncodingException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  TextView emojiText = (TextView)findViewById(R.id.emojitext);
  
  //byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x81};
  //byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x84};
  byte[] bytes = {(byte) 0xF0, (byte) 0x9F, (byte) 0x98, (byte) 0x89};
  try {
   emojiText.setText(new String(bytes, "UTF-8"));
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  //Direct type in the emoji
  //emojiText.setText("😁");  //maybe cannot displayed on browser

 }

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidemoji.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="lesapplication.blogspot.com"
        android:textSize="28dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/emojitext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="100dp"
        android:textStyle="bold" />

</LinearLayout>

The page Emoji Unicode Tables show commonly-supported Emoji that map to standardized Unicode characters.

0 Response to "Display emoji from byte[], encoded using UTF-8"

Posting Komentar