how to insert image to a editText

后端 未结 6 790
名媛妹妹
名媛妹妹 2020-12-09 00:06

I want to insert a image to a editText my code is:

  CharSequence charSeq= editText.getText()+\" \";
  SpannableString ss2 = new SpannableString(charSeq); 
          


        
6条回答
  •  被撕碎了的回忆
    2020-12-09 00:56

    Do something like this (note: you can reuse SpannableStringBuilder)

    editText = (EditText)mRoot.findViewById(R.id.content);
    ImageSpan imageSpan = new ImageSpan(preview);
    
    SpannableStringBuilder builder = new SpannableStringBuilder();
    builder.append(editText.getText());
    
    // this is a string that will let you find a place, where the ImageSpan is.
    String imgId = "[img=1]"; 
    
    int selStart = editText.getSelectionStart();
    
    // current selection is replaceв with imageId
    builder.replace(editText.getSelectionStart(), editText.getSelectionEnd(), imgId);
    
    // This adds a span to display image where the imageId is. If you do builder.toString() - the string will contain imageId where the imageSpan is.
    // you can use it later - if you want to find location of imageSpan in text;
    builder.setSpan(imageSpan, selStart, selStart + imgId.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.setText(builder);
    

    Note: See follow up answer for dealing with partial deletion of tags

提交回复
热议问题