Android TextView : How can I set background color of an entire line in TextView

标签 android textview background-color

我想在 TextView 中设置整行的背景颜色,而不一定是文本覆盖的那部分行(我可以使用 Span 来实现)。

例如如果说第 0 行,可以容纳 25 个字符,但只有 12 个字符。如果我说

SpannableString s = new SpannableString("abcdefghijkl");
s.setSpan(new BackgroundColorSpan(0xffffffff), 0, 11, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
TextView t = new TextView();
t.setText(s);

这将设置一半线的背景颜色。 但我想让整行(TextView 的整个宽度)都充满背景色。此外,我希望这只发生在一行中,而不是整个 TextView 背景。

知道如何实现吗?

最佳答案

将您的 TextView 包裹在 RelativeLayout 中,并在其后放置另一个 View :

<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 View 设置为该高度:

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);
    }
}

关于Android TextView : How can I set background color of an entire line in TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14282092/

相关文章:

Android 反向地理编码在 TextView 中不显示文本

java - Android 中的多个 View

android - 简单的自定义控件 - 强制关闭

Android Studio kotlin 聊天屏幕布局

基于Android Fragment的开源项目

java - 单击 Android ExpandableListView 会导致子项目出现 "ID Not Found"错误

Android Studio GridLayout onTouch 事件

android - Instagram 如何在故事模式中增加背景中的图像颜色

html - 如何更改超大屏幕的背景颜色?

android - 如何不从系统获取时间?