2013-01-11 143 views
2

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

E.g.如果说第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背景。

任何想法如何实现?

+0

检查:http://stackoverflow.com/questions/8105545/can-i-select-a-color-for-each-text-line-i-append-to-a-textview – EvZ

+0

没有这将仅设置具有文本的行的部分的背景。我希望整条线(甚至是空白空间)具有相同的背景颜色。 –

+0

我认为你应该改变11 s.length(),你将有你的字符串的总长度,并设置其背景 – Reda

回答

-1

的TextView(就像所有其他的Android设备上查看)有setBackgroundColor

t.setBackgroundColor(0xffffffff); 
+0

但是这会设置整个TextView的背景颜色。我只需要设置一行的背景颜色。 –

+0

哦...所以使用@dokkaebi答案! – Budius

+0

是的,dokkaebi的答案似乎是我可以用于我的要求的最合适的答案。我会探索这个。感谢你和@dokkaebi。 –

0

裹在RelativeLayout的你的TextView,并把它在其他视图的方法:

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

是的,这看起来像是一个解决方案。但我需要设置多于一行背景颜色。而且,如果用户滚动浏览线路怎么办?背景颜色视图如何移动? –

+0

哦,你想突出一个特定的线? – dokkaebi

+0

在这种情况下,我想我会去用一个ListView,并根据其宽度将文本分成几行。然后你可以免费获得线条突出显示。 – dokkaebi

0

您的目标是使用垂直方向的LineaLayout,
将TextView作为“可着色线条”。

1)创建一个扩展LinearLayout的类。
2)编写基本功能添加“着色线”,“画它”& e.t.c.
3)在布局XML中使用您的视图。

+0

谢谢,尽管dokkaebi的回答看起来最合适,并且对我来说最容易实现我所需要的东西,但是谢谢你提供了关于如何创建我自己的观点的想法。这会有所帮助。谢谢。 –

1
TextView name = (TextView) findViewById(R.id.name); 
    String iName = "YOYOYOYO"; 

    ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(184, 184, 
      184)); 

    SpannableString ssb = new SpannableString(iName); 
    ssb.setSpan(fcs, 0, iName.length(), 
      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    name.setText(ssb);