TextView 加載Html格式字符串

package com.example.htmltest;

import java.net.URL;

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

public class MainActivity extends Activity
{
    private String html;
    private TextView textView;
    public static DisplayMetrics displayMetrics;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        displayMetrics=getApplicationContext().getResources().getDisplayMetrics();
        html="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0\"><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><meta content=\"telephone=no\" name=\"format-detection\"></head><P><FONT size=5>【一汽-大衆諸暨元通】 —— 全心,全服務</FONT><SPAN style=\"COLOR: #000000\"><!--StartFragment --></P><DIV><FONT size=5>    9月27-29日,諸暨元通一汽-大衆全系現車秋季城市廣場金秋溫情大酬賓啦!對一汽-大衆大衆汽車感興趣的朋友亦可帶着家人,邀上朋友,結伴來城市廣場一汽-大衆展位,我們期待您的光臨</FONT><FONT size=5>!</FONT></DIV><DIV><FONT size=5>展位位置:</FONT></DIV><DIV><IMG style=\"WIDTH: 653px; HEIGHT: 388px\" height=673 src=\"/pro/iXs_Editor/uploadfile/20130925102136428.jpg\" width=1117 border=0></DIV><DIV> </DIV><DIV><FONT size=5>夢想隨行,國慶獻禮,諸暨元通一汽大衆金秋溫情大酬賓</FONT></DIV><DIV><FONT size=5></FONT> </DIV><DIV><IMG src=\"/pro/iXs_Editor/uploadfile/20130925102251145.jpg\" border=0></DIV><DIV><FONT size=4></FONT> </DIV><DIV><FONT size=4>願我們真心優質的服務,真摯誠懇的讓利,讓您盡享購車之旅的那份愉悅與享受!<BR>我們的使命是讓更多的人擁有一汽-大衆品牌轎車!<BR></FONT><FONT size=4><STRONG><FONT color=#ff0000>汽車之路,元通相伴,汽車生活,元通服務<BR></FONT></STRONG>享受更多優惠,盡在諸暨元通一汽-大衆4S店(原海越汽車)!<BR>一汽-大衆授權經銷商:諸暨元通汽車有限公司<BR>4S店地址:諸暨市環城西路167號(老辦證中心旁)<BR>銷售熱線:0575-87105555<BR>預約熱線:0575-87105501<BR>24小時救援熱線:13857521919</FONT></DIV><P align=left><IMG src=\"http://car.zhuji.net/pro/iXs_Editor/uploadfile/20130903090510258.jpg\" border=0></P><DIV> </DIV></SPAN>";
        textView=(TextView)findViewById(R.id.text);
        initContent(textView, html);
    }

    /**
     * 加載html數據
     * @param tv
     * @param s
     */
    private void initContent(TextView tv, String s)
    {
        tv.setMovementMethod(ScrollingMovementMethod.getInstance());// 設置可滾動  
        tv.setMovementMethod(LinkMovementMethod.getInstance());//設置超鏈接可以打開網頁  
        tv.setText(Html.fromHtml(s, new URLImageParser(textView, getApplicationContext()), null));
    }

    //這裏面的resource就是fromhtml函數的第一個參數裏面的含有的url  
    //無法加載大圖片
//    ImageGetter imgGetter = new Html.ImageGetter()
//    {
//        public Drawable getDrawable(String source)
//        {
//            Drawable drawable = null;
//            URL url;
//            try
//            {
//                if (!source.contains("http"))
//                {
//                    url = new URL("http://car.zhuji.net" + source);
//                }
//                else
//                {
//                    url = new URL(source);
//                }
//                drawable = Drawable.createFromStream(url.openStream(), ""); // 獲取網路圖片
//            }
//            catch (Exception e)
//            {
//                return null;
//            }
//            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
//                    drawable.getIntrinsicHeight());
//            return drawable;
//        }
//    };
}

package com.example.htmltest;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.provider.SyncStateContract.Constants;
import android.text.Html.ImageGetter;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class URLImageParser implements ImageGetter {
    Context c;
    TextView tv_image;
    private Drawable mDefaultDrawable;

    public URLImageParser(TextView t, Context c) {
        this.tv_image = t;
        this.c = c;

        try {
            mDefaultDrawable = c.getResources().getDrawable(
                    R.drawable.ic_launcher);
            // Log.i("-->", "執行");
        } catch (NotFoundException e) {
            mDefaultDrawable = null;
            // Log.i("-->", "執行1");
            e.printStackTrace();
        }
    }

    @Override
    public Drawable getDrawable(String source) {
        if (!source.contains("http"))
        {
            source="http://car.zhuji.net" + source;
        }
        
        // TODO Auto-generated method stub
        URLDrawable urlDrawable = new URLDrawable();
        // main3.b.add(source);
        try {
            /*
             * mDefaultDrawable.setBounds(0, 0, 0 +
             * mDefaultDrawable.getIntrinsicWidth(),
             * mDefaultDrawable.getIntrinsicHeight());
             */
            urlDrawable.drawable = mDefaultDrawable;
            URLImageParser.this.tv_image.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*
         * urlDrawable.setBounds(0, 0, 0 + mDefaultDrawable.getIntrinsicWidth(),
         * mDefaultDrawable.getIntrinsicHeight());
         */
        ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable);
        asyncTask.execute(source);
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected void onPostExecute(Drawable result) {
            if (result != null) {
                urlDrawable.drawable = result;
                URLImageParser.this.tv_image.invalidate();
                // Log.i("-->", "執行3");
            }
        }

        @Override
        protected void onPreExecute() {
            urlDrawable.setBounds(0, 0,
                    0 + mDefaultDrawable.getIntrinsicWidth(),
                    0 + mDefaultDrawable.getIntrinsicHeight());
            urlDrawable.drawable = mDefaultDrawable;
            URLImageParser.this.tv_image.invalidate();
            super.onPreExecute();
        }

        @Override
        protected Drawable doInBackground(String... params) {
            // TODO Auto-generated method stub
            String source = params[0];// 圖片URL
            return fetchDrawable(source);
        }

        // 獲取URL的Drawable對象
        public Drawable fetchDrawable(String urlString) {
            BitmapDrawable bitmap = null;
            Drawable drawable = null;
            try {
                InputStream is = fetch(urlString);
                bitmap = (BitmapDrawable) BitmapDrawable.createFromStream(is,"src");
                drawable = bitmap;
                
//                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
//                        drawable.getIntrinsicHeight());
                DisplayMetrics metrics = /*Constants.metrics*/MainActivity.displayMetrics;
                if(bitmap.getBitmap().getWidth()>metrics.widthPixels/2||bitmap.getBitmap().getHeight()>metrics.heightPixels/6)
                    //進行等比例縮放程序
//                    drawable.setBounds(0, 0, metrics.widthPixels/2, ((int)(metrics.widthPixels/2*bitmap.getBitmap().getHeight()/bitmap.getBitmap().getWidth())));
                    drawable.setBounds(0, 0, metrics.heightPixels/6*bitmap.getBitmap().getWidth()/bitmap.getBitmap().getHeight(), metrics.heightPixels/6);
                else
                    drawable.setBounds(0,0,bitmap.getBitmap().getWidth(),bitmap.getBitmap().getHeight());
            } catch (Exception e) {
                return null;
            }
            return drawable;
        }

        private InputStream fetch(String urlString)
                throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
    
     class URLDrawable extends BitmapDrawable {  
        protected Drawable drawable;  
        @Override  
        public void draw(Canvas canvas) {  
            
          if (drawable != null) {  
           drawable.draw(canvas);  
          }  
        }  
    }  
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章