未在textview Html.fromHtml方法中加载的图像

时间:2014-11-18 10:16:50

标签: java android html textview

我创建了一个简单的textview来显示html内容。文本显示良好,但图像没有显示。我已提及this下载图片。但结果是一样的。图像将替换为框。enter image description here

活动

package com.example.loadinghtmlinlist;

import java.util.HashMap;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.parse.FunctionCallback;
import com.parse.ParseCloud;
import com.parse.ParseObject;

public class PostListActivity extends Activity {
    TableLayout select_city_table;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_list);
        // Find the ListView resource.   
        select_city_table = (TableLayout) findViewById(R.id.select_city_table);
        setStory();
        cityListBody("Hello");
    }

    public void setStory(){

        // Pull data from Parse
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("userid", "xxxxxxxxx");
        params.put("skip", 0);

        ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
            @Override
            public void done(List<List<ParseObject>> arg0, com.parse.ParseException arg1){
                if (arg0 == null) {

                } else {
                    Log.e("size ", "RUNNING Size :   " + arg0.size());
                    if (arg0.size() == 0) {
                        Log.e("size is zero", "RUNNING BOOLEAN SOMETHING");

                    }

                    if (arg0.size() > 0) {

                    }
                    if (arg0.size() > 0) {
                        for (int i = 0; i < arg0.size(); i++) {
                            if(arg0.get(i).get(0).get("htmlContent") != null){
                               // INSERTOBJECTOGETDATA.GETDATA(arg0.get(i).get(0).getString("htmlContent"));
                                //Toast.makeText(PostListActivity.this, arg0.get(i).get(0).getString("htmlContent"), Toast.LENGTH_SHORT).show();
                                cityListBody(arg0.get(i).get(0).getString("htmlContent"));

                               }

                        }   
                    }
                }

            }

        });

    }

    // method to populate city body
        public void cityListBody(String strcity_name){
            // ----------------Select city
            // body------------------------------------------
            TableRow city_list_tr_data;
            city_list_tr_data = new TableRow(this);
            city_list_tr_data.setId(10);
            // city_list_tr_data.setBackgroundResource(R.drawable.grey_list_bg);
            city_list_tr_data.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            final TextView city_name = new TextView(this);
            city_name.setId(21);// define id that must be unique
            // no_of_types.setText(parser.getValue(e, KEY_RIGHTMARKS)); // set
            // the text for the header

            URLImageParser p = new URLImageParser(city_name, this);
            Spanned htmlSpan = Html.fromHtml(strcity_name, p, null);
            city_name.setText(htmlSpan);

            city_name.setText(Html.fromHtml(strcity_name));
            city_name.setTextColor(Color.BLACK); // set the color
            city_name.setPadding(5, 5, 5, 5); // set the padding (if required)
            city_name.setGravity(Gravity.CENTER);
            city_name.setTextSize(16);
            city_list_tr_data.addView(city_name); // add the column to
            // the table row
            // here



            select_city_table.addView(city_list_tr_data, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));



        }


}

URLImageParser类

package com.example.loadinghtmlinlist;

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.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html.ImageGetter;
import android.view.View;



public class URLImageParser implements ImageGetter {
    Context c;
    View container;

    /***
     * 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, 0 + result.getIntrinsicWidth(), 0 
                    + 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, 0 + drawable.getIntrinsicWidth(), 0 
                        + 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();
        }
    }
}

URLDrawable类

package com.example.loadinghtmlinlist;

import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

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);
        }
    }
}

我哪里错了?需要改变哪些才能正确显示图像?

应用Haresh Chhelana的建议后,输出显示图像但输出格式不正确: enter image description here

1 个答案:

答案 0 :(得分:1)

无需使用此代码:

city_name.setText(Html.fromHtml(strcity_name));

在此代码之前,您已使用URLImageParser创建了Spannable字符串,并将Spannable设置为city_name,因此上面的代码会使用Html.fromHtml内容覆盖Spannable内容。

更新代码:

@Override
 protected void onPostExecute(Drawable result) {
    result.setBounds(0, 0, result.getIntrinsicWidth(), result.getIntrinsicHeight());
    urlDrawable.setBounds(0, 0, result.getIntrinsicWidth(), result.getIntrinsicHeight());
    urlDrawable.drawable = result;
    URLImageParser.this.container.setMinimumHeight(result.getIntrinsicHeight());
    URLImageParser.this.container.requestLayout();
    URLImageParser.this.container.invalidate();
 }