TextView with two text colors on Android

2

I am receiving String frames from two different channels and I want to show them in a single TextView but with two different colors, for this I am using Html.fromHtml() to color the second frame, the color change works but for some reason eliminates the special characters of change of lines ("\ n") and the textview shows it like this:

When it should instead the textview should show:

Here is my code, can someone tell me how to correct this?

 mDumpTextView = (TextView) findViewById(R.id.tv1_ReadValues);
 mScrollView = (ScrollView) findViewById(R.id.sc1_Scroller);
 .
 .

 public void handleMessage(Message msg) {
        switch (msg.what) {
            case UsbService.SYNC_READ:
                String buffer = (String) msg.obj;
                if(msg.arg1 == 0){
                    mActivity.get(). mDumpTextView.append(buffer);
                }else if(msg.arg1 == 1){
                     mActivity.get().mDumpTextView.append( Html.fromHtml( redB + buffer + colorEnd ) );
                     mScrollView.smoothScrollTo( 0, mDumpTextView.getBottom() );
                }
                break;
        }
    }
    
asked by W1ll 14.12.2018 в 19:22
source

1 answer

1

In this case I suggest replacing the \n with <br>

  String buffer = (String) msg.obj;
  buffer = buffer.replaceAll("\n", "<br>");

In this way using Html.fromHtml(...) the line breaks will be represented.

  

<br> The HTML line break element produces a jump of line in the   text (carriage return).

Example:

    TextView textView = findViewById(R.id.welcomeText);

    String buffer = "Hola\n<font color=\"green\">amigo</font>\n<font color=\"#ff9900\">Stackoverflow</font>...\n<font color=\"red\">e foarte mișto!</font>\n<b>Jorgesys</b>";

    buffer = buffer.replaceAll("\n", "<br>");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        textView.setText(Html.fromHtml(buffer, Html.FROM_HTML_MODE_LEGACY));
    } else {
        textView.setText(Html.fromHtml(buffer));
    }

In the TextView it will show the following information:

    
answered by 14.12.2018 / 19:26
source