Android将图像插入EditText

时间:2017-09-24 06:22:22

标签: android

我正在尝试使用以下代码将一些图像添加到EditText中:

Bitmap myBitmap = BitmapFactory.decodeFile(APP.DIR_APP + APP.IMAGE + "/ok.png");

Drawable mDrawable = new BitmapDrawable(getResources(), myBitmap);

ImageSpan imageSpan = new ImageSpan(mDrawable);

SpannableStringBuilder builder = new SpannableStringBuilder();

builder.append(contentText.getText());
String imgId = "[img=1]";

int selStart = contentText.getSelectionStart();
builder.replace(contentText.getSelectionStart(), contentText.getSelectionEnd(), imgId);

builder.setSpan(imageSpan, selStart, selStart + imgId.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
contentText.setText(builder);

此路径为APP.DIR_APP + APP.IMAGE + "/ok.png"是正确的,我用file.exists()检查并且返回true,但我没有将所选图像转换为edittext

1 个答案:

答案 0 :(得分:2)

别忘了打电话 mDrawable.setBounds(0, 0, myBitmap.getWidth(), myBitmap.getHeight())。 要么 mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());

目前您的边界设置为0,0,0,0 - 因此,您无法看到自己的图像。它是零大小的。

如果要缩放图像,可以设置其他边界。

不要忘记为不同的屏幕密度缩放图像。