Reputation: 1
I have added a clicklistener to the spannableString, and I want to get the local path of the imageSpan when I click it, so that I can pass the path to the new activity to display the original image. I have used the method getSource() of imageSpan, but the method just returns null to me.I can't find the way to solve it.I need help!
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);
}
});
The imageSpan is added to the spanned as below,insertBitmap which is public get a bitmap with the path passed from the former activity and call the insertBitmap which is private, and the private insertBitmap generates the imageSpan and then insert it into the 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);
}
Upvotes: 0
Views: 113