2016-12-07 92 views
1

我正在創建一種類似於終端的視圖,它將顯示通過藍牙接收和傳輸的消息,收到藍色消息,以紅色傳輸。ScrollView中的Android TextView - 每條新線的顏色不同

到目前爲止,我設法把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) 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

非常感謝!

回答

0

你可以做一個有點棘手編輯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)); 
} 
+0

一件事...當我用Html.fromHtml(),該方法似乎排除「\ n」個符號。我做了什麼,我基本上使用scrollTextView.append(「\ n」);在下一行。這可行,但也許有另一種方法使用相同的Html.fromHtml()方法使用換行符號?否則,非常感謝! – Niklavs

+0

太棒了!這是一個很好的小技巧要知道,你永遠不知道什麼時候在'TextView'中需要一個小的HTML。 – Illdapt

+0

是的,你應該能夠使用HTML的'
'標籤。只需添加'String colorEnd =「
」'試一試。 – Illdapt

相關問題