【发布时间】:2021-03-13 05:40:44
【问题描述】:
我在 Textview 中为 android:background 属性创建了一个自定义可绘制对象。
但是我只希望 TextView 的某个部分而不是整个 TextView 的可绘制背景
到目前为止完成的工作:
目标:我想实现这样的目标(即只为 substring(1,2) 的文本设置背景):
这就是我目前取得的成果:
overline.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="-2dp"
android:left="-2dp"
android:right="-2dp"
android:top="1dp">
<shape android:shape="rectangle">
<stroke
android:width="1dp"
android:color="#030310" />
</shape>
</item>
</layer-list>
layout.xml
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/overline"
android:textColor="#030310"
android:text="Hello"/>
这是我到目前为止所尝试的:
SpannableString ss = new SpannableString("Hello");
Drawable d = ContextCompat.getDrawable(((MainActivity) getActivity()).getApplicationContext(), R.drawable.overline);
d.setBounds(0, 0, 30, 30);
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 1, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
myTextView.setText(ss);
我不太了解 ImageSpan,因此这是我在尝试上述代码后得到的结果(我在从 MainActivity 加载的 Fragment 中编写此代码),
【问题讨论】: