私は単純なチャット アプリケーションを実行しており、メッセージの書き込み中に edittext にスマイリーを表示したいと考えています。
ImageSpan を介して Image によって置換される文字を識別するためにこれを使用します (これは、EditText にスマイリー文字が挿入された場合にのみ呼び出されます)。
for (index = start; index < start+num_chars; index++) {
if (index + 1 > editable.length())
continue;
if(emoticons.containsKey(editable.subSequence(index, index + 1).toString())){
int length=1;
Drawable drawable = context.getResources().getDrawable(emoticons.get(editable.subSequence(index, index + 1).toString()));
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
int size=Utils.GetDipsFromPixel(context, (int)(textSize*1.3));
Drawable d = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, size, size, true));
int dWidth = d.getIntrinsicWidth();
int dHeight = d.getIntrinsicHeight();
d.setBounds(0 , -dHeight, dWidth, 0);
ImageSpan span;
span = new ImageSpan(d,ImageSpan.ALIGN_BASELINE);
editable.setSpan(span, index, index + length,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
}
}
スパンを設定するために SPAN_EXCLUSIVE_EXCLUSIVE タグを使用していますが、swiftkey キーボードに問題があります。これは、編集テキストにスマイリーを挿入すると、imageSpan の直後に書き込むすべてが画像の下に保持されるためです (SPAN_EXCLUSIVE_INCLUSIVE など)。Android のデフォルト キーボードでは、この問題は発生しません。
EditTextのスマイリーと同じ動作のwhatsappアプリケーションのみが必要です。
助言がありますか?コードに変更を加える必要がありますか?
編集:「編集可能な」変数がメソッドに渡されます。txtMessage が EditText である txtMessage.getText() 値です。
ありがとう!
編集: コードの 1 つの部分のみにまたがってください! これは複数行でうまく機能します!問題は、Drawable->Bitmap->ResizedBitmap->Drawable の使用にあったと思います。
public static final HashMap<String, Integer> emoticons = new HashMap();
static {
emoticons.put("\ue415", R.drawable.e415);
emoticons.put("\ue056", R.drawable.e056);
emoticons.put("\ue057", R.drawable.e057);
...
public static Spannable getSmiledText(Context context, Spannable editable,
int start, int num_chars, float textSize) {
int index;
for (index = start; index < start + num_chars; index++) {
if (index + 1 > editable.length())
continue;
if (EmojiLayout.emoticons.containsKey(editable.subSequence(index,
index + 1).toString())) {
int length = 1;
Bitmap smiley = BitmapFactory.decodeResource(context.getResources(), ((Integer) EmojiLayout.emoticons.get(editable.subSequence(index,
index + 1).toString())));
int size = Utils.GetDipsFromPixel(context,
(int) (textSize * 1.37));
Bitmap scaledbmp=Bitmap.createScaledBitmap(
smiley, size, size, false);
ImageSpan span;
span = new ImageSpan(scaledbmp);
Log.d("EmojiLayout", "Index: " + String.valueOf(index) + "To: "
+ String.valueOf(index + length));
editable.setSpan(span, index, index + length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
}
}
return editable;
}