HasaniK HasaniK - 11 days ago 5
Android Question

Image doesn't display in SpannableString with Image

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

The image doesn't appear when joined with another SpannableString. It works only as a single SpannableString.
However I need to join multiple SpannableStrings with & without images.

Thanks for your input.

Answer

create a SpannableStringBuilder to append multiple imagespan and text

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

and finally set

editText.setText(builder);

Note though SpannableStringBuilder is an immutable class it can't be changed.

Comments