androidandroid-layouttextviewspannablestringspannable

How can I raise up the position of a particular character with Span?


There is a simple characters. "Hello → world!!!"

it's good to see it in XML Design tab. Nothing wrong.

but when i run the app, and the arrow is located at the baseline of TextView.

this is a xml code and design tab. the photo in XML and code

and the result when i run this app.

enter image description here

I don't understand how the result is.

so I want to put the arrow in the middle like when i see it in the XML Design tab.

how can i do this? can i use Spannable? or Something??


Solution

    1. You can TextView use android:gravity="center_vertical|left"
    2. Here's a trick to help: You can include an image of special characters and insert that image into the output text.

    First, add a new Drawable resource file (ic_arrow.xml) in res/drawable, and copy and paste it into it.

    <vector android:alpha="0.78" android:height="24dp"
      android:viewportHeight="24.0" android:viewportWidth="24.0"
      android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
      <path android:fillColor="#FF000000" android:pathData="M3,12L21.5,12"
        android:strokeColor="#000000" android:strokeWidth="1"/>
      <path android:fillColor="#FF000000" android:pathData="M21,12L17,8"
        android:strokeColor="#000000" android:strokeWidth="1"/>
      <path android:fillColor="#FF000000" android:pathData="M21,12L17,16"
        android:strokeColor="#000000" android:strokeWidth="1"/>
    </vector>
    

    Add code to the activity.

        TextView textView = findViewById(R.id.my_text_view);
    
        Drawable arrow = ContextCompat.getDrawable(this, R.drawable.ic_arrow);
        Float ascent = textView.getPaint().getFontMetrics().ascent;
        int h = (int) -ascent;
        arrow.setBounds(0,0,h,h);
    
        SpannableString stringWithImage = new SpannableString("A*B");
        stringWithImage.setSpan(new ImageSpan(arrow, DynamicDrawableSpan.ALIGN_BASELINE), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(stringWithImage);  
    

    It works like this.

    enter image description here