Android TextView解析HTML内容

最后显示的结果如下:
Android TextView解析HTML内容_第1张图片


下面这张图实现异步下载图片,同时对html内容正确的显示
这里写图片描述



package com.example.textimage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.Gravity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    private String html = "欧盟

"
+ "乌克兰
"
+ "
俄罗斯
"
+ "
美国"
+ "
"
; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textTV); NetworkImageGetter imageGetter = new NetworkImageGetter(); Spanned spanned = Html.fromHtml(html, imageGetter, null); // 图片文字居中显示 tv.setGravity(Gravity.CENTER_HORIZONTAL); tv.setText(spanned); } private final class NetworkImageGetter implements Html.ImageGetter { @Override public Drawable getDrawable(String source) { // TODO Auto-generated method stub LevelListDrawable d = new LevelListDrawable(); new LoadImage().execute(source, d); return d; } } /**** 异步加载图片 **/ private final class LoadImage extends AsyncTask<Object, Void, Bitmap> { private LevelListDrawable mDrawable; @Override protected Bitmap doInBackground(Object... params) { String source = (String) params[0]; mDrawable = (LevelListDrawable) params[1]; try { InputStream is = new URL(source).openStream(); return BitmapFactory.decodeStream(is); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { if (bitmap != null) { BitmapDrawable d = new BitmapDrawable(bitmap); mDrawable.addLevel(1, 1, d); mDrawable .setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); // mDrawable.setBounds(0, 0, // getWindowManager().getDefaultDisplay().getWidth(), // bitmap.getHeight()); mDrawable.setLevel(1); CharSequence t = tv.getText(); tv.setText(t); } } } @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; } }


FR:徐海涛(Hunk Xu)

你可能感兴趣的:(Android)