如何使用 Span 提高特定角色的位置?

问题描述

一个简单的字符。 “你好→世界!!!”

很高兴在 XML 设计选项卡中看到它。没有错。

但是当我运行应用程序时,箭头位于 TextView 的基线处。

这是一个 xml 代码和设计选项卡。

the photo in XML and code

以及我运行这个应用程序时的结果。

enter image description here

我不明白结果如何。

所以我想把箭头放在中间,就像我在 XML 设计选项卡中看到的那样。

我该怎么做?我可以使用 Spannable 吗?或者什么??

解决方法

  1. 您可以使用 TextView android:gravity="center_vertical|left"
  2. 这里有一个技巧可以帮助您:您可以添加特殊图片 字符并将该图像插入到输出文本中。

首先在res/drawable中添加一个新的Drawable资源文件(ic_arrow.xml),复制粘贴进去。

<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,16"
    android:strokeColor="#000000" android:strokeWidth="1"/>
</vector>

向活动添加代码。

    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,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);  

它是这样工作的。

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...