将您的 TextView 包装在一个 RelativeLayout 中,并在其后面放置另一个视图:
<RelativeLayout
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<View android:id="@+id/bgcolor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@color/whatever"
/>
<TextView android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
现在,在全局布局中,找到 TextView 的一行的高度,并将 bgcolor 视图设置为该高度:
final TextView textView = (TextView) findViewById(R.id.textview);
final ViewTreeObserver vto = textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int lineHeight = textView.getLineHeight();
// May need to also getLineSpacingExtra, etc. not sure.
View bgColor = findViewById(R.id.bgcolor);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)
bgColor.getLayoutParams();
lp.height = lineHeight;
bgColor.setLayoutParams(lp);
// May or may not want to remove the listener:
vto.removeGlobalOnLayoutListener(this);
}
}