Remove extra line breaks after Html.fromHtml()

后端 未结 4 1591
花落未央
花落未央 2020-12-13 03:49

I am trying to place html into a TextView. Everything works perfectly, this is my code.

String htmlTxt = \"

Hellllo

\"; // the html is form
相关标签:
4条回答
  • 2020-12-13 04:27

    Nice answer @Christine. I wrote a similar function to remove trailing whitespace from a CharSequence this afternoon:

    /** Trims trailing whitespace. Removes any of these characters:
     * 0009, HORIZONTAL TABULATION
     * 000A, LINE FEED
     * 000B, VERTICAL TABULATION
     * 000C, FORM FEED
     * 000D, CARRIAGE RETURN
     * 001C, FILE SEPARATOR
     * 001D, GROUP SEPARATOR
     * 001E, RECORD SEPARATOR
     * 001F, UNIT SEPARATOR
     * @return "" if source is null, otherwise string with all trailing whitespace removed
     */
    public static CharSequence trimTrailingWhitespace(CharSequence source) {
    
        if(source == null)
            return "";
    
        int i = source.length();
    
        // loop back to the first non-whitespace character
        while(--i >= 0 && Character.isWhitespace(source.charAt(i))) {
        }
    
        return source.subSequence(0, i+1);
    }
    
    0 讨论(0)
  • 2020-12-13 04:31

    You can try this:

    Spanned htmlDescription = Html.fromHtml(textWithHtml);
    String descriptionWithOutExtraSpace = new String(htmlDescription.toString()).trim();
    
    textView.setText(htmlDescription.subSequence(0, descriptionWithOutExtraSpace.length()));
    
    0 讨论(0)
  • 2020-12-13 04:38

    you can use this lines ... totally works ;)

    i know your problem solved but maybe some one find this useful .

    try{
            string= replceLast(string,"<p dir=\"ltr\">", "");
            string=replceLast(string,"</p>", "");
    }catch (Exception e) {}
    

    and here is replaceLast ...

    public String replceLast(String yourString, String frist,String second)
    {
        StringBuilder b = new StringBuilder(yourString);
        b.replace(yourString.lastIndexOf(frist), yourString.lastIndexOf(frist)+frist.length(),second );
        return b.toString();
    }
    
    0 讨论(0)
  • 2020-12-13 04:41

    The spannable is a CharSequence, which you can manipulate.

    This works:

        myTextView.setText(noTrailingwhiteLines(html));
    
        private CharSequence noTrailingwhiteLines(CharSequence text) {
    
            while (text.charAt(text.length() - 1) == '\n') {
                text = text.subSequence(0, text.length() - 1);
            }
            return text;
        }
    
    0 讨论(0)
提交回复
热议问题