imageandroid-edittextspannablestringbuilder

How to add multiple image into EditText using spannable or any other way?


I am creating a note taking app, I have done text section and its working properly. Also database working properly. But I want to add image in the EditText. When user add an image, it will place at the EditText cursor position and this task will happen for multiple image. And save the EditText entities (text and image) in SQL Lite database.

Please help someone to do this job. Thank you.

I have tried this job in onActivityResult , but image are not showing

if(requestCode==1 && resultCode==RESULT_OK && data!=null) {
    Uri imageUri= data.getData();
    try {
        InputStream inputStream= getContentResolver().openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        final Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        final ImageSpan imageSpan = new ImageSpan(drawable,ImageSpan.ALIGN_BOTTOM);
        Spannable span = new SpannableStringBuilder(editText.getText().toString()+"\n");
        span.setSpan(imageSpan, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.append(span, 0, ("\n").length());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Solution

  • You are replacing zero characters when you do the following:

    span.setSpan(imageSpan, 0, 0, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    

    You will need to replace at least one character. Since you are inserting an ImageSpan, you will need to add at least one character to replace.

    ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
    Editable editable = editText.getText();
    // Insert a single space to replace.
    editable = editable.insert(0, " ");
    editable.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.setText(editable);