想在EditText和TextView控件中随时插入手机本地图片,主要借助于android提供的两个类ImageSpan和SpannableString。如,在EditText中插入图片,分为3步:
1、扫描手机,选择图片:
Intent的Type设置为image/*表示任意格式的图片
private void choosePictureFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, CHOOSEPICTUREFROMGALLERY);
}
2、重写Activity的onActivityResult()方法:
case CHOOSEPICTUREFROMGALLERY:
if (data != null) { Uri uri_picture = data.getData(); ContentResolver resolver = CreateNewDiaryActivity.this.getContentResolver(); Cursor cursor = resolver.query(uri_picture, null, null, null, MediaStore.Images.Media.DATE_MODIFIED); cursor.moveToFirst(); int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA); picturePath = cursor.getString(idx); Bitmap bitmap = BitmapFactory.decodeFile(picturePath); if (bitmap != null) { SpannableString pictureString = getBitmapMime(bitmap, uri_picture); insertPictureToEditText(pictureString); }
cursor.close();
3、注意到插入图片用到了两个方法getBitmapMime()和insertPictureToEditText():
private SpannableString getBitmapMime(Bitmap bitmap, Uri uri) {
String path = uri.getPath();
SpannableString ss = new SpannableString(path);
ImageSpan span = new ImageSpan(CreateNewDiaryActivity.this, bitmap);
ss.setSpan(span, 0, path.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return ss;
}
方法getBitmapMime作用是将插入的图片以ImageSpan表示,并替换掉uri.getPath,放入到SpannableString中,此时图片作为SpannableString字符串返回。
private void insertPictureToEditText(SpannableString ss) {
Editable et = et_content.getText();
int start = et_content.getSelectionStart();
et.insert(start, ss);
et_content.setText(et);
contentPictureStart = start;
contentPictureEnd = start + ss.length();
et_content.setSelection(start + ss.length());
et_content.setFocusable(true);
et_content.setFocusableInTouchMode(true);
}
方法insertPictureToEditText,首先创建EditText的Editale对象,将SpannableString插入到EditText的编辑位置,插入结束后修改EditText的编辑位置,至此,图片成功插入到文字中。
在TextView中插入图片也是一样的道理:
Bitmap bitmap = ImageProcess.resizeBitmap(diary_picPath, 100, 100);
ImageSpan imageSpan = new ImageSpan(mContext, bitmap);
SpannableString spannableString = new SpannableString("pic");
spannableString.setSpan(imageSpan, 0, spannableString.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
picture_tv.setText(spannableString);