【问题标题】:Android TextView in ScrollView - Different color for each new lineScrollView 中的 Android TextView - 每个新行的颜色不同
【发布时间】:2016-12-07 21:22:57
【问题描述】:

我正在创建一种类似终端的视图,它将显示通过蓝牙接收和传输的消息,例如收到的消息是蓝色的,发送的消息是红色的。

到目前为止,我设法将 textView 放在 scrollView 中,并通过使用 .append() 方法在滚动视图中添加行。

布局如下:

    <ScrollView
    android:id="@+id/scrollingView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/disconnectButton"
    android:layout_alignParentStart="true">

    <TextView
        android:text="Received and sent txt!!!\n"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollTextView"
        android:minLines="11"
        android:maxLines="11"/>
</ScrollView> 

以及向scrollView添加文本的代码:

scrollView = (ScrollView) findViewById(R.id.scrollingView);
scrollTextView = (TextView) findViewById(R.id.scrollTextView);
scrollTextView.setGravity(Gravity.BOTTOM); scrollTextView.setTextColor(getResources().getColor(R.color.receivedBTColor));
scrollTextView.append("$"+dataInPrint+"\n");
scrollView.fullScroll(View.FOCUS_DOWN);

问题是每条线都应该能够有不同的颜色。 setTextColor() 方法为整个 textView 设置颜色,这完全不是我想要的,因为我需要临时保存向上移动的行,直到 scrollView 溢出。我看了使用 Spannable 类的例子,但是比较乱。

谁能提出一种制作可滚动彩色文本的方法?像这样的东西? Example from Bluetooth terminal app

非常感谢!

【问题讨论】:

    标签: android text colors terminal scrollview


    【解决方案1】:

    您可以使用 HTML 和 Android 的 Html.fromHtml() 进行一些棘手的编辑...

    String dataInPrint = "" //Whatever the output message is.
    
    String redB = "<font color="red">";
    String blueB = "<font color="blue">";
    String colorEnd = "</font>";
    
    if(//message is send){
        yourtextview.append(Html.fromHtml(redB + dataInPrint + colorEnd));
    }
    else{//message is recieve
        yourtextview.append(Html.fromHtml(blueB + dataInPrint + colorEnd));
    }
    

    【讨论】:

    • 还有一件事...当我使用 Html.fromHtml() 时,该方法似乎排除了“\n”符号。我所做的,我基本上使用了 scrollTextView.append("\n");在下一行。这可行,但也许还有另一种方法可以使用相同的 Html.fromHtml() 方法来使用换行符?否则,非常感谢!!!
    • 太棒了!这是一个很好的小技巧,你永远不知道TextView 中何时需要一点 HTML
    • 是的,您应该能够使用 HTML 的 &lt;br&gt; 标签。只需添加 String colorEnd = "&lt;/font&gt;&lt;br&gt;" 即可尝试。
    • 你也可以试试yourtextview.append(Html.fromHtml(blueB + dataInPrint + colorEnd) + "\n");,虽然我还没有测试过
    • 利用 HTML 的
      标签有效!但是,最后一个建议没有奏效。文本附加了换行符,但颜色没有改变。
    猜你喜欢
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多