图像不会在带有图像的SpannableString中显示

时间:2016-11-23 04:54:54

标签: android spannablestring

import static android.text.TextUtils.join;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List; 

public class MainActivity extends AppCompatActivity {

TextView testText;
TextView testText2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    testText = (TextView) findViewById(R.id.text1);
    testText2 = (TextView) findViewById(R.id.text2);

    List<SpannableString> refinements = new ArrayList<>();
    refinements.add(getFilterWithIcon("100", R.drawable.ic_feature_bed_s));
    refinements.add(new SpannableString("Testing text"));

    //Text without icon
    testText.setText(join(" | ", refinements));
    //Text with icon 
    testText2.setText(getFilterWithIcon("100", R.drawable.ic_feature_bed_s));

}

private SpannableString getFilterWithIcon(String stringValue, int icon) {
    Drawable image = ContextCompat.getDrawable(getApplicationContext(), icon);
    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
    ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    String spString = "  " + stringValue;
    SpannableString spFilterWithIcon = new SpannableString(spString);
    spFilterWithIcon.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return spFilterWithIcon;
}}

Result

与另一个SpannableString连接时,图像不会出现。它仅作为单个SpannableString工作。 但是我需要加入多个SpannableStrings和&amp;没有图像。

感谢您的意见。

1 个答案:

答案 0 :(得分:2)

创建一个SpannableStringBuilder以附加多个图像范围和文本

SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(edittext.getText());
builder.append(getFilterWithIcon("100", R.drawable.ic_feature_bed_s));

最后设置

editText.setText(builder);

注意虽然SpannableStringBuilder是一个不可变类,但它无法更改。