简体   繁体   English

Android显示HTML文本的最佳方法

[英]Android best way to display html text

I have string with html tags , links , image links so what is the best way to display this string? 我有带有html tagslinksimage links字符串,那么显示此字符串的最佳方法是什么? I know that people using Webview for that but maybe there is a way to do it in textview without putting too much work? 我知道人们为此使用Webview ,但是也许有一种方法可以在textview中完成它而又不花费太多工作? Because with WebView comes different problems for example if you want to change text color you need to add extra style to that string. 因为WebView带来不同的问题,例如,如果您想更改文本颜色,则需要为该字符串添加额外的样式。 I'm interested in ways to make links clickable and displaying Images in the same textview. 我对使链接可单击并在同一textview中显示图像的方法感兴趣。

Try using this :- Try using this

Html.fromHtml("your html code");

Example :- Example :-

txtvw.setText(Html.fromHtml("<p align=right> <b> "
        + "Hi!" + " <br/> <font size=6>"
        + " How are you "+"</font> <br/>"
        + "I am fine" + "  </b> </p>"));

Output :- Output :-

Hi 你好
How are you 你好吗
I am fine 我很好

**Full Code With Image And Hyperlink** :- **Full Code With Image And Hyperlink** :-

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class MainActivity extends Activity {

 String htmlString = "<img src='ic_launcher'><i>Welcome to<i> <b><a href='https://stackoverflow.com/'>Stack Overflow</a></b>";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  TextView htmlTextView = new TextView(this);
  setContentView(htmlTextView);

  htmlTextView.setText(Html.fromHtml(htmlString, new Html.ImageGetter(){

   @Override
   public Drawable getDrawable(String source) {
    Drawable drawable;
    int dourceId = 
      getApplicationContext()
      .getResources()
      .getIdentifier(source, "drawable", getPackageName());

    drawable = 
      getApplicationContext()
      .getResources()
      .getDrawable(dourceId);

    drawable.setBounds(
      0, 
      0, 
      drawable.getIntrinsicWidth(),
      drawable.getIntrinsicHeight());

    return drawable;
   }

  }, null));

  htmlTextView.setMovementMethod(LinkMovementMethod.getInstance());

 }

}

To support all API use this function :- To support all API use this function :-

@SuppressWarnings("deprecation")
public static Spanned fromHtml(String html) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY);
    }
    else {
        return Html.fromHtml(html);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM