Android點滴---TextView,RadioButton 設定 HTML文本,載入網狀圖片

來源:互聯網
上載者:User

標籤:android   textview   radiobutton   checkbox   textview使用html   


現在在做一個題庫類的項目,由於有些數學符號或者化學符號之類的沒辦法直接在最上層顯示,所以就使用了圖文混排;

後台返回的資料直接是HTML格式的資料。


所以就開始去研究控制項如何去顯示HTML


先貼上參考的文章,感謝分享!


1、這種只適合載入本地圖片,或者相容版本在4.0以下

Android中Textview顯示帶html文本二-------【Textview顯示本地圖片】


上面這種方式,只要在百度上搜一下 Android TextView 設定 HTML 資料,就會找出來很多類似的,但是感覺這為大神寫的最好!


如果HTML資料中,只有文本的話,使用下面的寫法就Ok了,

        //如果 HTML資料中沒有圖片,僅僅是文本的話,直接這樣設定就好了        String html = "<p>這個就是測試</p><span>資料</span><img src=\"http://as114.com/pic/logo.png\" />";                TextView mTvHello = (TextView) this.findViewById(R.id.tv_hello);        mTvHello.setText(Html.fromHtml(html));


如果HTML資料中包含本地圖片路徑,你可以參考上面連結裡,這位大神些的兩種方式就可以了

        //主要是多了這個載入圖片的參數        Html.ImageGetter imageGetter = new Html.ImageGetter() {            @Override            public Drawable getDrawable(String source) {                                //實現方式可以參考上面的文章,根據自己的需求來實現                return null;            }        };        //Html。fromHtml時  加上上面的參數        mTvHello.setText(Html.fromHtml(html,imageGetter,null));


其實如果你的項目只相容到 4.0以下,並且不怕卡的話,上面的文章裡也有實現方式(但是這種需求估計現在沒有!)

說一下原因,4.0以下是可以再主線程請求網路的,但是4.0以後是不可以在主線程請求網路,

        url = new URL(source);        drawable = Drawable.createFromStream(url.openStream(), "");

上面這種寫法就要在主線程載入圖片, 雖然4.0以下可以使用,但是如果圖片大的話,估計就直接卡死了,所以還是不要用了!

如果是本地圖片的話,可以使用文章中的兩種圖片方式,根據自己的需求來實現就OK了;


2、非同步載入HTML中的圖片  參考文章(stackoverflow 上的,有時候可以能訪問不了,自己找辦法……)

Android HTML ImageGetter as AsyncTask


上面的文章完美解決了問題!

貼出代碼,省的部分朋友不能訪問文章,看不了代碼


import android.graphics.Canvas;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;/** * Created by Administrator on 2015/4/30. */public class URLDrawable extends BitmapDrawable{    // the drawable that you need to set, you could set the initial drawing    // with the loading image if you need to    protected Drawable drawable;    @Override    public void draw(Canvas canvas) {        // override the draw to facilitate refresh function later        if(drawable != null) {            drawable.draw(canvas);        }    }}

package com.jddl.tvhtmldemo;import android.content.Context;import android.graphics.drawable.Drawable;import android.os.AsyncTask;import android.text.Html;import android.view.View;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;/** * Created by Administrator on 2015/4/30. */public class URLImageParser implements Html.ImageGetter {    Context c;    View container;    @Override    protected Object clone() throws CloneNotSupportedException {        return super.clone();    }    /**     * Construct the URLImageParser which will execute AsyncTask and refresh the container     *     * @param t     * @param c     */    public URLImageParser(View t, Context c) {        this.c = c;        this.container = t;    }    public Drawable getDrawable(String source) {        URLDrawable urlDrawable = new URLDrawable();        // get the actual source        ImageGetterAsyncTask asyncTask =                new ImageGetterAsyncTask(urlDrawable);        asyncTask.execute(source);        // return reference to URLDrawable where I will change with actual image from        // the src tag        return urlDrawable;    }    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {        URLDrawable urlDrawable;        public ImageGetterAsyncTask(URLDrawable d) {            this.urlDrawable = d;        }        @Override        protected Drawable doInBackground(String... params) {            String source = params[0];            return fetchDrawable(source);        }        @Override        protected void onPostExecute(Drawable result) {            // set the correct bound according to the result from HTTP call            urlDrawable.setBounds(0, 0, result.getIntrinsicWidth(), result.getIntrinsicHeight());            // change the reference of the current drawable to the result            // from the HTTP call            urlDrawable.drawable = result;            // redraw the image by invalidating the container            URLImageParser.this.container.invalidate();        }        /**         * Get the Drawable from URL         *         * @param urlString         * @return         */        public Drawable fetchDrawable(String urlString) {            try {                InputStream is = fetch(urlString);                Drawable drawable = Drawable.createFromStream(is, "src");                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());                return drawable;            } catch (Exception e) {                return null;            }        }        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();        }    }    public URLImageParser() {        super();    }}



由於我的項目中有選擇題,和單選題,所以我用到了 TextView , RadioButton  和  CheckBox 三種控制項,

下面是使用時的代碼

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        TextView mTvHello = (TextView) this.findViewById(R.id.tv_hello);        String html = "<p>這個就是測試</p><span>資料</span><img src=\"http://as114.com/pic/logo.png\" />";        mTvHello.setMovementMethod(ScrollingMovementMethod.getInstance());        URLImageParser urlImgGetter = new URLImageParser(mTvHello, this);        mTvHello.setText(Html.fromHtml(html, urlImgGetter, null));        RadioButton mRbHtml = (RadioButton) this.findViewById(R.id.rb_html);        URLImageParser urlImgGetterRb = new URLImageParser(mRbHtml, this);        mRbHtml.setText(Html.fromHtml(html, urlImgGetterRb, null));        CheckBox mCbHtml = (CheckBox) this.findViewById(R.id.cb_html);        URLImageParser urlImgGetterCb = new URLImageParser(mCbHtml, this);        mRbHtml.setText(Html.fromHtml(html, urlImgGetterCb, null));    }}

簡單說一下我的理解(小弟 從事Android 不長,如有理解錯誤還請大家多多指教!)


URLImageParser 類實現了 Html.ImageGetter 介面, 寫法和別的沒什麼區別,

在getDrawable先返回一個urlDrawable,是一個空的圖片


然後使用,非同步載入圖片,載入完成後在重新整理圖片和View

思路貌似很簡單,但是之前沒想著怎麼實現!

再次感謝分享!


因為大多數都是寫的TextView 使用的方法,

但是我想: 因為RadioButton 和 Checkbox 都是 TextView  的子類,所以應該也可以使用!

最終測試證明的想法是可行的,貼上 運行照片




Android點滴---TextView,RadioButton 設定 HTML文本,載入網狀圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.