How to use shape as drawable in imagespan

2

I have an imageSpan, but it only works with images, when I try to use a shape the location of the image is as if there is no image, but it does not show any errors.

       String text = exercicios.get(0).getPergunta();
    Log.i(TAG, exercicios.get(0).getPergunta());
    //String text = "texto # texto";

    //Posição onde colocar a imegem(posição da marca)
    int imagePos = text.indexOf("#");

    //Criar um SpannableString do texto
    SpannableString spannableString = new SpannableString(text);

    //Obter o drawable a inserir
    Drawable drawable = getResources().getDrawable(R.drawable.shapepergunta);
    drawable.setBounds(0, 0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());

    //Criar um ImageSpan do drawable
    ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
    //Inserir a imagem(ImageSpan) no texto(SpannableString)
    spannableString.setSpan(imageSpan,imagePos,imagePos+1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
    //Atribuir o texto com a imagem ao TextView
    txvpergunta.setText(spannableString);

Shape:

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
android:radius="14dp"
/>
<gradient
android:angle="45"
android:centerX="35%"
android:centerColor="#198CFF"
android:startColor="#449DEF"
android:endColor="#2F6699"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<stroke
android:width="1dp"
android:color="#878787"
/>
</shape>
    
asked by anonymous 16.01.2018 / 12:19

1 answer

1

The way shape is declared it has no dimensions.

When it's used as background or foreground of another view , that's fine, since it fits the dimension of the view.

When used as span this does not happen. So you have to define your dimensions.

You can do this in two ways:

  • Including the size attribute in xml:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <size
            android:width="32dp"
            android:height="16dp"/>
        <corners
            android:radius="14dp"/>
        <gradient
            android:angle="45"
            android:centerX="35%"
            android:centerColor="#198CFF"
            android:startColor="#449DEF"
            android:endColor="#2F6699"
            android:type="linear"/>
        <padding
            android:left="0dp"
            android:top="0dp"
            android:right="0dp"
            android:bottom="0dp"/>
        <stroke
            android:width="1dp"
            android:color="#878787"/>
    </shape>
    
  • In Java via setBounds() :

    //Obter o drawable a inserir
    Drawable drawable = getResources().getDrawable(R.drawable.shapepergunta);
    drawable.setBounds(0, 0, 64, 32);
    
17.01.2018 / 15:49