android tutorial textview parses the html example with pictures
- 2020-05-24 06:08:20
- OfStack
public class MainActivity extends Activity {
private Handler handler;
private String html;
private TextView tv;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Looking for online html data
html = "<html><head><title>TextView use HTML</title></head><body><p><strong> Emphasis on </strong></p><p><em> italics </em></p>"
+ "<p><a href=\"https://www.ofstack.com"> hyperlinks HTML An introduction to </a> learning HTML!</p><p><font color=\"#aabb00\"> color 1"
+ "</p><p><font color=\"#00bbaa\"> color 2</p><h1> The title 1</h1><h3> The title 2</h3><h6> The title 3</h6><p> Is greater than > Less than <</p><p>"
+ " Here is the web image </p><img src=\"https://www.ofstack.com/1207.jpg\"/></body>"
+ " Here is the web image </p><img src=\"https://www.ofstack.com/207.jpg\"/></body></html>";
tv = (TextView) this.findViewById(R.id.id);
bar = (ProgressBar) this.findViewById(R.id.id_bar);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());// rolling
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 0x101) {
bar.setVisibility(View.GONE);
tv.setText((CharSequence) msg.obj);
}
super.handleMessage(msg);
}
};
// Because downloading pictures from the Internet is time-consuming So start a new thread
Thread t = new Thread(new Runnable() {
Message msg = Message.obtain();
@Override
public void run() {
// TODO Auto-generated method stub
bar.setVisibility(View.VISIBLE);
/**
* To achieve the image display needs to use Html.fromHtml the 1 Four reconstruction methods: public static Spanned
* fromHtml (String source, Html.ImageGetterimageGetter,
* Html.TagHandler
* tagHandler) Among them Html.ImageGetter is 1 We are going to implement this interface in its getDrawable
* (String source) Method that returns a picture Drawable Objects can.
*/
ImageGetter imageGetter = new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
URL url;
Drawable drawable = null;
try {
url = new URL(source);
drawable = Drawable.createFromStream(
url.openStream(), null);
drawable.setBounds(0, 0,
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return drawable;
}
};
CharSequence test = Html.fromHtml(html, imageGetter, null);
msg.what = 0x101;
msg.obj = test;
handler.sendMessage(msg);
}
});
t.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}