4

以下のメソッドからaTextViewを設定したい:SpannableString

Html.fromHtml(String source, Html.ImageGetter imageGetter, 
   Html.TagHandler tagHandler)

ただし、ImageGetterここでは以下のメソッドをオーバーライドする必要があります。

public abstract Drawable getDrawable(String source)

インターネットからドローアブルを取得する必要があるため、非同期で行う必要があり、そうではないようです。

それを機能させる方法は?ありがとう。

4

3 に答える 3

14

これらの人は素晴らしい仕事をしました.Squareのピカソライブラリを使用した私のソリューションです:

//...
final TextView textView = (TextView) findViewById(R.id.description);
        Spanned spanned = Html.fromHtml(getIntent().getStringExtra(EXTRA_DESCRIPTION),
                new Html.ImageGetter() {
                    @Override
                    public Drawable getDrawable(String source) {
                        LevelListDrawable d = new LevelListDrawable();
                        Drawable empty = getResources().getDrawable(R.drawable.abc_btn_check_material);;
                        d.addLevel(0, 0, empty);
                        d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
                        new ImageGetterAsyncTask(DetailActivity.this, source, d).execute(textView);

                        return d;
                    }
                }, null);
        textView.setText(spanned);
//...


class ImageGetterAsyncTask extends AsyncTask<TextView, Void, Bitmap> {


    private LevelListDrawable levelListDrawable;
    private Context context;
    private String source;
    private TextView t;

    public ImageGetterAsyncTask(Context context, String source, LevelListDrawable levelListDrawable) {
        this.context = context;
        this.source = source;
        this.levelListDrawable = levelListDrawable;
    }

    @Override
    protected Bitmap doInBackground(TextView... params) {
        t = params[0];
        try {
            Log.d(LOG_CAT, "Downloading the image from: " + source);
            return Picasso.with(context).load(source).get();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void onPostExecute(final Bitmap bitmap) {
        try {
            Drawable d = new BitmapDrawable(context.getResources(), bitmap);
            Point size = new Point();
            ((Activity) context).getWindowManager().getDefaultDisplay().getSize(size);
            // Lets calculate the ratio according to the screen width in px
            int multiplier = size.x / bitmap.getWidth();
            Log.d(LOG_CAT, "multiplier: " + multiplier);
            levelListDrawable.addLevel(1, 1, d);
            // Set bounds width  and height according to the bitmap resized size
            levelListDrawable.setBounds(0, 0, bitmap.getWidth() * multiplier, bitmap.getHeight() * multiplier);
            levelListDrawable.setLevel(1);
            t.setText(t.getText()); // invalidate() doesn't work correctly...
        } catch (Exception e) { /* Like a null bitmap, etc. */ }
    }
}

私の 2 セント. 平和!

于 2015-04-17T18:31:10.957 に答える
4

今、私は AsyncTask を使って画像をダウンロードしていますImageGetter:

Spanned spannedContent = Html.fromHtml(htmlString, new ImageGetter() {

        @Override
        public Drawable getDrawable(String source) {
            new ImageDownloadAsyncTask().execute(textView, htmlString, source);
            return null;
        }
    }, null);

そしてTextView、画像がダウンロードされたら、テキストを再度設定します。

今では動作します。TextView.postInvalidate()しかし、ダウンロードした画像を再描画しようとすると失敗しました。setText()でやり直さなければなりませんAsyncTask

誰かが理由を知っていますか?

于 2010-09-22T07:06:26.997 に答える
4

これは、html文字列内のすべての画像を取得する私のコードです(元のものから単純化されているので、うまくいくことを願っています):

private HashMap<String, Drawable> mImageCache = new HashMap<String, Drawable>();
private String mDescription = "...your html here...";

private void updateImages(final boolean downloadImages) {
    if (mDescription == null) return;
    Spanned spanned = Html.fromHtml(mDescription,
        new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(final String source) {
            Drawable drawable = mImageCache.get(source);
            if (drawable != null) {
                return drawable;
            } else if (downloadImages) {
                new ImageDownloader(new ImageDownloader.ImageDownloadListener() {
                    @Override
                    public void onImageDownloadComplete(byte[] bitmapData) {
                        Drawable drawable = new BitmapDrawable(getResources(),
                                BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length));
                        try {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        } catch (Exception ex) {}
                        mImageCache.put(source, drawable);
                        updateImages(false);
                    }
                    @Override
                    public void onImageDownloadFailed(Exception ex) {}
                }).execute(source);
            }
            return null;
        }
    }, null);
    tvDescription.setText(spanned);
}

つまり、基本的にここで起こることは、ImageGetter が html 記述内のすべての画像に対してリクエストを行うということです。その画像が mImageCache 配列になく、downloadImages が true の場合、非同期タスクを実行してその画像をダウンロードします。完了すると、ドローアブルをハッシュマップに追加し、このメソッドを再度呼び出します (ただし、downloadImages を false にして、無限ループのリスクを回避します)。二度目の試み。

これで、私が使用した ImageDownloader クラスが必要になります。

public class ImageDownloader extends AsyncTask {
    public interface ImageDownloadListener {
        public void onImageDownloadComplete(byte[] bitmapData);
        public void onImageDownloadFailed(Exception ex);
    }

    private ImageDownloadListener mListener = null;

    public ImageDownloader(ImageDownloadListener listener) {
        mListener = listener;
    }

    protected Object doInBackground(Object... urls) {
        String url = (String)urls[0];
        ByteArrayOutputStream baos = null;
        InputStream mIn = null;
        try {
            mIn = new java.net.URL(url).openStream();
            int bytesRead;
            byte[] buffer = new byte[64];
            baos = new ByteArrayOutputStream();
            while ((bytesRead = mIn.read(buffer)) > 0) {
                if (isCancelled()) return null;
                baos.write(buffer, 0, bytesRead);
            }
            return new AsyncTaskResult<byte[]>(baos.toByteArray());

        } catch (Exception ex) {
            return new AsyncTaskResult<byte[]>(ex);
        }
        finally {
            Quick.close(mIn);
            Quick.close(baos);
        }
    }

    protected void onPostExecute(Object objResult) {
        AsyncTaskResult<byte[]> result = (AsyncTaskResult<byte[]>)objResult;
        if (isCancelled() || result == null) return;
        if (result.getError() != null) {
            mListener.onImageDownloadFailed(result.getError());
        }
        else if (mListener != null)
            mListener.onImageDownloadComplete(result.getResult());
    }
}
于 2013-08-01T22:59:20.960 に答える