问题:为什么ImageSpan的ALIGN_BASELINE无法精确对齐基线,如何解决对齐问题?
在我的活动中,我创建了一个SpannableString,并用ImageSpan代替字符串的一部分。 ImageSpan使用一个24x24像素的纯黑png图像,并设置为ALIGN_BASELINE。
我在我的布局中有两个视图:一个
正如您所看到的,该行与
在我的活动中,我创建了一个SpannableString,并用ImageSpan代替字符串的一部分。 ImageSpan使用一个24x24像素的纯黑png图像,并设置为ALIGN_BASELINE。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myTextView = findViewById(R.id.myTextView);
SpannableString ss = new SpannableString("Hello world!");
Drawable d = ContextCompat.getDrawable(this, R.drawable.box);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(imageSpan, 2, 5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
myTextView.setText(ss);
}
}
我在我的布局中有两个视图:一个
TextView
和一个用于显示基线的 View
。<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff9800"
android:textSize="48sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:layout_width="match_parent"
android:layout_height="1px"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBaseline_toBaselineOf="@id/myTextView"
android:background="#de4caf50"/>
</android.support.constraint.ConstraintLayout>
正如您所看到的,该行与
TextView
的基线正确对齐,但是 ImageSpan
稍微低于基线。