如何使用 Span 提升特定角色的位置?
How can I raise up the position of a particular character with Span?
有一个简单的字符。 “你好 → 世界!!!”
很高兴在 XML 设计选项卡中看到它。没问题。
但是当我 运行 应用程序时,箭头位于 TextView 的基线。
这是一个 xml 代码和设计选项卡。
以及我 运行 这个应用程序时的结果。
不明白结果如何
所以我想把箭头放在中间,就像我在 XML 设计选项卡中看到的那样。
我该怎么做?我可以使用 Spannable 吗?还是什么??
- 您可以使用 TextView android:gravity="center_vertical|left"
- 这里有一个技巧可以提供帮助:您可以添加一张特殊图片
字符并将该图像插入到输出文本中。
首先在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,12L17,16"
android:strokeColor="#000000" android:strokeWidth="1"/>
</vector>
将代码添加到 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);
它是这样工作的。
有一个简单的字符。 “你好 → 世界!!!”
很高兴在 XML 设计选项卡中看到它。没问题。
但是当我 运行 应用程序时,箭头位于 TextView 的基线。
这是一个 xml 代码和设计选项卡。
以及我 运行 这个应用程序时的结果。
不明白结果如何
所以我想把箭头放在中间,就像我在 XML 设计选项卡中看到的那样。
我该怎么做?我可以使用 Spannable 吗?还是什么??
- 您可以使用 TextView android:gravity="center_vertical|left"
- 这里有一个技巧可以提供帮助:您可以添加一张特殊图片 字符并将该图像插入到输出文本中。
首先在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,12L17,16"
android:strokeColor="#000000" android:strokeWidth="1"/>
</vector>
将代码添加到 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);
它是这样工作的。