Ali
Ali

Reputation: 11

Android Attach Image between text with SpannableStringBuilder

Sory for my english. I want attach image from gallery and show in edit text with SpannableStringBuilder. I have success for get Image Path from Gallery. After picture selected, Picture Show. But, for the second attach image picture not show and first image attach became a text. any one give me solution ? big thanks. this is my code:

private void IntentPict() {
    Intent intent = new Intent(); 
    intent.setType("image/*"); 
    intent.setAction(Intent.ACTION_GET_CONTENT); 
    startActivityForResult(Intent.createChooser(intent, "Select File"),MY_INTENT_CLICK);        
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK){
        if (requestCode == MY_INTENT_CLICK){
            if (null == data) return;

            String selectedImagePath;
            Uri selectedImageUri = data.getData();

            //there is no problem with get path
            selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);  

            //pathImag is ListArray<String>
            pathImg.add(selectedImagePath);

            addImageBetweentext(pathImg);
        }
    }
}

private void addImageBetweentext(ArrayList<String> listPath) {
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    for(int i=0;i<listPath.size();i++){
        String path = listPath.get(i);
        Drawable drawable = Drawable.createFromPath(path);
        drawable.setBounds(0, 0, 400, 400);

        ssb.append(mBodyText+"\n");         
        ssb.setSpan(new ImageSpan(drawable), ssb.length()-(path.length()+1), 
            ssb.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    }
    mBodyText.setText(ssb);
}

Upvotes: 0

Views: 3097

Answers (1)

N.T.
N.T.

Reputation: 2611

Here's something that should work. I am loading resource drawables instead, just because it was quicker for me to validate, but I tried to keep as mich as possible for your original flow and variable names:

Drawable[] drawables = new Drawable[2];
drawables[0] = getResources().getDrawable(R.drawable.img1);
drawables[1] = getResources().getDrawable(R.drawable.img2);

SpannableStringBuilder ssb = new SpannableStringBuilder();
for (int i = 0; i < drawables.length; i++) {
    Drawable drawable = drawables[i];
    drawable.setBounds(0, 0, 400, 400);

    String newStr = drawable.toString() + "\n";
    ssb.append(newStr);
    ssb.setSpan(
            new ImageSpan(drawable),
            ssb.length() - newStr.length(),
            ssb.length() - "\n".length(),
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
mBodyText.setText(ssb);

Long story short: the start position for the incremental builder needs to be set to the current length of it, minus what you just added.

Upvotes: 1

Related Questions