我给spannableString添加了一个clicklistener,我想在点击的时候获取imageSpan的本地路径,这样就可以把路径传给新的activity来显示原图。我使用了imageSpan的getSource()方法,但是该方法只是返回null给我。我找不到解决方法。我需要帮助!
noteContent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Spanned s = noteContent.getText();//得到Spanned对象
ImageSpan[] image_spans = s.getSpans(0, s.length(), ImageSpan.class); //得到该EditText中多有的ImageSpan对象
int selectStart = noteContent.getSelectionStart(); //获得当前EditText中的光标位置
Log.i("info", "cursor: " + selectStart);
int i = 0;
//遍历所有的ImageSpan 根据光标位置判断点击的是哪一个ImageSpan
for (ImageSpan span : image_spans) {
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
String path = span.getSource();
Log.i("info", "start:" + start + ",end:" + end + ",image path:" + path + ",times" + i);
if (selectStart >= start && selectStart <= end) {
//Toast.makeText(getApplicationContext(), "点击了图片", Toast.LENGTH_LONG).show();
Intent intent = new Intent(NoteActivity.this,PictureDisplayer.class);
intent.putExtra("PATH",path);
i += 1;
startActivity(intent);
}
}
Log.i("info", "times:" + i);
}
});
imageSpan添加到spanned如下,public的insertBitmap用前一个activity传递的路径获取位图,调用private的insertBitmap,private的insertBitmap生成imageSpan,然后插入到spannableString中。
private SpannableString insertBitmap(String path, Bitmap bitmap) {
Editable edit_text = getEditableText();
int index = getSelectionStart(); // get the location of the cursor
//插入换行符,使图片单独占一行
SpannableString newLine = new SpannableString("\n");
edit_text.insert(index, newLine);//插入图片前换行
// 创建一个SpannableString对象,以便插入用ImageSpan对象封装的图像
path = mBitmapTag + path + mBitmapTag;
SpannableString spannableString = new SpannableString(path);
// 根据Bitmap对象创建ImageSpan对象
ImageSpan imageSpan = new ImageSpan(mContext, bitmap);
// 用ImageSpan对象替换你指定的字符串
spannableString.setSpan(imageSpan, 0, path.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// 将选择的图片追加到EditText中光标所在位置
if (index < 0 || index >= edit_text.length()) {
edit_text.append(spannableString);
} else {
edit_text.insert(index, spannableString);
}
edit_text.insert(index, newLine);//插入图片后换行
return spannableString;
}
/**
* 插入图片
*
* @param path
*/
public void insertBitmap(String path) {
Bitmap bitmap = getSmallBitmap(path, 480, 800);
insertBitmap(path, bitmap);
}