问题描述
有一个简单的字符。 “你好→世界!!!”
很高兴在 XML 设计选项卡中看到它。没有错。
但是当我运行应用程序时,箭头位于 TextView 的基线处。
以及我运行这个应用程序时的结果。
我不明白结果如何。
所以我想把箭头放在中间,就像我在 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,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);
它是这样工作的。