如何将图像插入editText

时间:2011-10-19 08:24:21

标签: android android-edittext

我想将图像插入editText,我的代码是:

  CharSequence charSeq= editText.getText()+" ";
  SpannableString ss2 = new SpannableString(charSeq); 
  Drawable d2 = holder.image.getDrawable(); 
  d2.setBounds(0, 0, d2.getIntrinsicWidth(), d2.getIntrinsicHeight()); 

  ImageSpan span2 = new ImageSpan(d2, ImageSpan.ALIGN_BASELINE); 
  ss2.setSpan(span2,charSeq.length()-1, charSeq.length(),  

  Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

  editText.setText(ss2,BufferType.SPANNABLE); 

我的代码可以运行,但我有一些不错的经验,我想修改:

1:你知道什么时候使用ss2.setSpan()方法,图像可以替换字符,我只想插入新图像,不要想图像替换字符。

2:你知道我的方法包括“editText.getText()+”“;”,我添加了一些额外的空格,以便图像可以插入最后的CharSequence。如何不需要添加一些额外的,图像也插入最后的CharSequence。

3.当我将图像插入CharSequence的最后一个时,光标不在最后,它出现在CharSequence的前面。如何将光标放在图像后面。

4.i想在不同的CharSequence中不断插入图像,怎么办?

我的问题很多,我希望你能帮助我,非常感谢你。

6 个答案:

答案 0 :(得分:10)

执行类似的操作(注意:您可以重用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);

注意:有关处理部分标签删除的信息,请参阅follow up answer

答案 1 :(得分:3)

试试这个,我希望你在寻找这个:

   <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/icon">
    </EditText>

你可以尝试同样的事情:

android:drawableRight
android:drawableTop
android:drawableBottom
android:drawablePadding

答案 2 :(得分:2)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewWithImages extends TextView {

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextViewWithImages(Context context) {
        super(context);
    }
    @Override
    public void setText(CharSequence text, BufferType type) {
        Spannable s = getTextWithImages(getContext(), text);
        super.setText(s, BufferType.SPANNABLE);
    }

    private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();

    private static boolean addImages(Context context, Spannable spannable) {
        Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
        boolean hasChanges = false;

        Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
             && spannable.getSpanEnd(span) <= matcher.end()
               ) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
        int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
        if (set) {
            hasChanges = true;
            spannable.setSpan(  new ImageSpan(context, id),
                                matcher.start(),
                                matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                             );
        }
    }

        return hasChanges;
    }
    private static Spannable getTextWithImages(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addImages(context, spannable);
        return spannable;
    }
}

使用:

res / layout / mylayout.xml 中的

            <com.xyz.customandroid.TextViewWithImages
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FFFFFF00"
                android:text="@string/can_try_again"
                android:textSize="12dip"
                style=...
                />
res / values / strings.xml 中的

<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>

其中 ok16.png retry16.png 位于 res / drawable / 文件夹中

答案 3 :(得分:1)

我想,你还需要一些文本编辑功能:如果删除了一个字符,应删除图像;这个类可以帮助(如果删除了它的char,则删除所有图像文本占位符)

public class ImageSpanTextWatcher implements TextWatcher {
    Object[] mTouchedSpans;
    int[] mSpanLength;
    boolean replacing = false;

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (s instanceof SpannableStringBuilder) {
            SpannableStringBuilder ssb = (SpannableStringBuilder) s;
            mTouchedSpans = ssb.getSpans(start, start + count, ImageSpan.class);
            if (mTouchedSpans != null && mTouchedSpans.length > 0) {
                mSpanLength = new int[mTouchedSpans.length];
                for (int i = 0; i < mTouchedSpans.length; i++) {
                    mSpanLength[i] = ssb.getSpanEnd(mTouchedSpans[i]) - ssb.getSpanStart(mTouchedSpans[i]);
                }
            }
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s instanceof SpannableStringBuilder) {
            SpannableStringBuilder ssb = (SpannableStringBuilder) s;

            if (replacing)
                return;
            replacing = true;
            if (mTouchedSpans != null && mTouchedSpans.length > 0)
                for (int i = 0; i < mTouchedSpans.length; i++) {
                    int newLen = ssb.getSpanEnd(mTouchedSpans[i]) - ssb.getSpanStart(mTouchedSpans[i]);
                    if (newLen < mSpanLength[i]) {
                        ssb.replace(ssb.getSpanStart(mTouchedSpans[i]), ssb.getSpanEnd(mTouchedSpans[i]), "");
                    }
                }
            mTouchedSpans = null;
            mSpanLength = null;
            replacing = false;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {}
}

答案 4 :(得分:1)

我是通过这种方式在EditText中插入和删除图像:

客户按钮插入

private void addImageInEditText(Drawable drawable) {

        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

        int selectionCursorPos = messageEditText.getSelectionStart();
        messageEditText.getText().insert(selectionCursorPos, ".");
        selectionCursorPos = messageEditText.getSelectionStart(); 
        SpannableStringBuilder builder = new SpannableStringBuilder(messageEditText.getText());
        int startPos = selectionCursorPos - ".".length();
        builder.setSpan(new ImageSpan(drawable), startPos, selectionCursorPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        messageEditText.setText(builder);
        messageEditText.setSelection(selectionCursorPos);
    }

自定义按钮删除

private void deleteImageFromEditText() {
        String msgEditText = messageEditText.getText().toString();
        LOGE(TAG, "text length : " + msgEditText.length());
        if (msgEditText.length() > 0) {
            int selectionCursorPos = messageEditText.getSelectionStart();
            int endPosition = messageEditText.getText().length();
            LOGE(TAG, "cursor Pos: " + selectionCursorPos + " endPosition : " + endPosition);

            if (selectionCursorPos > 0) {
                int deletingObjectStartPos = selectionCursorPos - 1;
                messageEditText.getText().delete(deletingObjectStartPos, selectionCursorPos);
                messageEditText.setSelection(deletingObjectStartPos);
            }
        } else {
            messageEditText.setText("");
        }
    }

Drawable可以通过多种方式进行测试我这样做:

Drawable drawable = getResources().getDrawable(R.drawable.ic_action_filter);
addImageBetweentext(drawable);

答案 5 :(得分:-1)

通过这个,您可以使图像左对齐,也可以在图像后获得光标。尝试使用:

mEditText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon,0, 0,0);