EmojiImageView in Android
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.res.ResourcesCompat;
public class EmojiImageView extends AppCompatImageView {
public EmojiImageView(Context context) {
super(context);
}
public EmojiImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setEmoji(int codePoint) {
Drawable emojiDrawable = ResourcesCompat.getDrawable(getResources(), getEmojiResource(codePoint), null);
setImageDrawable(emojiDrawable);
}
private int getEmojiResource(int codePoint) {
String codePointHex = Integer.toHexString(codePoint);
String resourceName = "emoji_" + codePointHex;
return getResources().getIdentifier(resourceName, "drawable", getContext().getPackageName());
}
}
To use this EmojiImageView in your layout XML file, you can use the following code:
<com.yourpackage.EmojiImageView
android:id="@+id/emoji_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In your Java or Kotlin code, you can set the emoji image by calling the setEmoji
method, like this:
EmojiImageView emojiImageView = findViewById(R.id.emoji_image_view);
emojiImageView.setEmoji(0x1F600); // set grinning face emoji
Remember to replace "yourpackage" with the package name of your app. Also, make sure that you have added the emoji image resources to the "res/drawable" folder with filenames in the format "emoji_{codepoint_hex}.xml".