2013-04-23 51 views
7

所以我使用ImageGetter來顯示來自JSON博客文章的圖像。我在日誌中獲取正確的源代碼,但是當URL達到setBounds時URL會發生變化。有任何想法嗎?Html.ImageGetter TextView

代碼:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_blog_view); 

    Intent intent = getIntent(); 
    Uri blogUri = intent.getData(); 
    mPost = blogUri.toString(); 
    mUrl = getIntent().getStringExtra("mUrl"); 

    TextView textView = (TextView) findViewById(R.id.scrollView1); 
    textView.setText(Html.fromHtml(mPost, imgGetter, null)); 
} 

private ImageGetter imgGetter = new ImageGetter(){ 
    @Override 
    public Drawable getDrawable(String source){ 
     Drawable drawable = Drawable.createFromPath(source); 
     try { 
      drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); 
     }catch (NullPointerException e){ 
      logException(e); 
     } 
     return drawable; 
    } 
}; 

「源」 的嘗試之前

http://www.domain.com/images_blog/feature.png

但在捕獲錯誤是:

無法解碼流:

java.io.FileNotFoundException: /http:/www.domain.com/images_blog/feature.png : open failed: ENOENT (No such file or directory) 
+0

仔細閱讀文檔Drawable.createFromPath() – pskink 2013-04-23 21:23:49

+0

所以我假設你說我應該使用Drawable.createFromStream(),正確嗎? – JMP 2013-04-23 22:34:37

+0

是的,但你也可以創建一些緩存,然後createFromPath可以使用 – pskink 2013-04-24 06:42:41

回答

43

最簡單的解決方法是:

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

import org.pskink.soom.R; 

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.Html.ImageGetter; 
import android.text.Spanned; 
import android.util.Log; 
import android.widget.TextView; 

public class TestImageGetter extends Activity implements ImageGetter { 
    private final static String TAG = "TestImageGetter"; 
    private TextView mTv; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test_image_getter); 
     String source = "this is a test of <b>ImageGetter</b> it contains " + 
       "two images: <br/>" + 
       "<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" + 
       "<img src=\"http://developer.android.com/assets/images/icon_search.png\">"; 

     Spanned spanned = Html.fromHtml(source, this, null); 
     mTv = (TextView) findViewById(R.id.text); 
     mTv.setText(spanned); 
    } 

    @Override 
    public Drawable getDrawable(String source) { 
     LevelListDrawable d = new LevelListDrawable(); 
     Drawable empty = getResources().getDrawable(R.drawable.ic_launcher); 
     d.addLevel(0, 0, empty); 
     d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight()); 

     new LoadImage().execute(source, d); 

     return d; 
    } 

    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]; 
      Log.d(TAG, "doInBackground " + source); 
      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) { 
      Log.d(TAG, "onPostExecute drawable " + mDrawable); 
      Log.d(TAG, "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.setLevel(1); 
       // i don't know yet a better way to refresh TextView 
       // mTv.invalidate() doesn't work as expected 
       CharSequence t = mTv.getText(); 
       mTv.setText(t); 
      } 
     } 
    } 
} 

有重新佈局一個不太優雅的方式下載圖像後一個TextView:

// i don't know yet a better way to refresh TextView 
// mTv.invalidate() doesn't work as expected 
CharSequence t = mTv.getText(); 
mTv.setText(t); 

如果有人知道更好的解決方案,請讓我知道

+0

謝謝你會試試這個。 – JMP 2013-04-25 19:28:01

+0

thnxxxxxxxxxxxxxxxxxxxxxxx – 2014-08-27 09:19:38

+0

如何將圖像url顯示到imageview – Prasad 2014-08-28 06:39:04

2

如果您有mTV(我的意思是TextView),您可以根據其尺寸(mTv.getWidth()和mTv.getHeight())和創建的位圖(bitmap.getWidth()和bitmap.getHeight())將這些值設置爲TextView(mTv)的新維度。

 if (bitmap != null) { 
      BitmapDrawable d = new BitmapDrawable(bitmap); 
      mDrawable.addLevel(1, 1, d); 
      int width = mTv.getWidth() < bitmap.getWidth() ? mTv.getWidth() : bitmap.getWidth(); 
      int height = bitmap.getHeight() * width/bitmap.getWidth(); 
      mDrawable.setBounds(0, 0, width, height); 
      mDrawable.setLevel(1); 
      // i don't know yet a better way to refresh TextView 
      // mTv.invalidate() doesn't work as expected 
      // but we can calculate new TextView dimensions 
      mTv.setHeight(height); 
      CharSequence t = mTv.getText(); 
      mTv.setText(t); 
     } 
+0

補充您的答案: 'final float scale = c.getResources()。getDisplayMetrics()。density; mDrawable.setBounds(0,0,Math.round(width * scale),Math.round(height * scale));' – 2017-11-10 18:01:34

1

此答案可能有幫助。我用Jsoup從字符串中提取<Img/>標記,然後我在Textview中顯示ImageView<p>中的圖像。結果是根據我需要的。此外,我用通用圖像加載器Libaray加載圖像在ImageView然後我添加視圖以編程方式佈局在我的情況佈局是linearlayout所以我做了一個助手類,並通過內容,HTML字符串和線性佈局作爲參數。

在您的項目中添加jsoup。

compile 'org.jsoup:jsoup:1.9.2' 

這裏有一些片段。

public class PostContentHandler { 
Context context; 
String content; 
LinearLayout linearLayout; 

public PostContentHandler(Context context, String content, LinearLayout linearLayout) { 
    this.context = context; 
    this.content = content; 
    this.linearLayout = linearLayout; 

} 

public void setContentToView() { 

    //custom font 
    Typeface bitterBoldFont = Typeface.createFromAsset(context.getAssets(), "fonts/Bitter-Regular.otf"); 

    List<String> p = new ArrayList<>(); 
    List<String> src = new ArrayList<>(); 
    List<String> li = new ArrayList<>(); 
    Document doc = Jsoup.parse(content); 

    Elements elements = doc.getAllElements(); 

    for (Element element : elements) { 
     Tag tag = element.tag(); 
     if (tag.getName().matches("h[1-6]{1}")) { 
      String heading = element.select(tag.getName().toString()).text(); 
      TextView textView = new TextView(context); 
      textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT)); 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); 
      int top = (int) context.getResources().getDimension(R.dimen.heading_margin_top); 
      int start = (int) context.getResources().getDimension(R.dimen.content_margin); 
      int end = (int) context.getResources().getDimension(R.dimen.content_margin); 
      params.setMargins(start, top, end, 0); 
      textView.setTextSize(20); 
      textView.setTypeface(bitterBoldFont); 
      textView.setText(heading); 
      textView.setTextColor(context.getResources().getColor(R.color.black)); 
      linearLayout.addView(textView); 
     } 
if (tag.getName().equalsIgnoreCase("p")) { 
      element.select("img").remove(); 
      String body = element.html(); 
      TextView textView = new TextView(context); 
      textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT)); 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); 
      int top = (int) context.getResources().getDimension(R.dimen.heading_margin_top); 
      int start = (int) context.getResources().getDimension(R.dimen.content_margin); 
      int end = (int) context.getResources().getDimension(R.dimen.content_margin); 
      params.setMargins(start, top, end, 0); 
      textView.setTypeface(bitterBoldFont); 
      textView.setLinksClickable(true); 
      textView.setAutoLinkMask(Linkify.WEB_URLS); 
      textView.setText(Html.fromHtml(body)); 
      textView.setTextColor(context.getResources().getColor(R.color.content_color)); 
      linearLayout.addView(textView); 
      p.add(body); 
     } 
     if (tag.getName().equalsIgnoreCase("ol")) { 
      String ol = element.select(tag.getName().toString()).outerHtml(); 
      TextView textView = new TextView(context); 
      textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT)); 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); 
      params.setMarginStart((int) context.getResources().getDimension(R.dimen.content_margin)); 
      int top = (int) context.getResources().getDimension(R.dimen.heading_margin_top); 
      int start = (int) context.getResources().getDimension(R.dimen.content_margin); 
      int end = (int) context.getResources().getDimension(R.dimen.content_margin); 
      params.setMargins(start, top, end, 0); 
      textView.setTypeface(bitterBoldFont); 
      textView.setLinksClickable(true); 
      textView.setAutoLinkMask(Linkify.WEB_URLS); 
      textView.setTextColor(context.getResources().getColor(R.color.content_color)); 
      textView.setText(Html.fromHtml(ol, null, new MyTagHandler())); 
      linearLayout.addView(textView); 

     } 
     if (tag.getName().equalsIgnoreCase("ul")) { 
      String ul = element.select(tag.getName().toString()).outerHtml(); 
      TextView textView = new TextView(context); 

      textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT)); 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); 
      int top = (int) context.getResources().getDimension(R.dimen.heading_margin_top); 
      int start = (int) context.getResources().getDimension(R.dimen.content_margin); 
      int end = (int) context.getResources().getDimension(R.dimen.content_margin); 
      params.setMargins(start, top, end, 0); 
      textView.setTypeface(bitterBoldFont); 
      textView.setLinksClickable(true); 
      textView.setAutoLinkMask(Linkify.WEB_URLS); 
      textView.setTextColor(context.getResources().getColor(R.color.content_color)); 
      textView.setText(Html.fromHtml(ul, null, new MyTagHandler())); 
      linearLayout.addView(textView); 
     } 
     if (tag.getName().equalsIgnoreCase("img")) { 
      String url = element.select("img").attr("src"); 
      final ImageView imageView = new ImageView(context); 
      imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT)); 
      final ProgressBar progressBar = new ProgressBar(context); 
      linearLayout.addView(progressBar); 
      progressBar.setVisibility(View.GONE); 
      ImageLoader imageLoader = ImageLoader.getInstance(); 
      imageLoader.displayImage(url, imageView, new SimpleImageLoadingListener() { 
       @Override 
       public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { 
        super.onLoadingComplete(imageUri, view, loadedImage); 
        progressBar.setVisibility(View.INVISIBLE); 
        int height = loadedImage.getHeight(); 
        imageView.getLayoutParams().height = getScreenWidth(); 
        imageView.setAdjustViewBounds(true); 
        imageView.requestLayout(); 
       } 

       @Override 
       public void onLoadingStarted(String imageUri, View view) { 
        super.onLoadingStarted(imageUri, view); 
        progressBar.setVisibility(View.VISIBLE); 
       } 
      }); 
      linearLayout.addView(imageView); 
      src.add(url); 
     } 

    } 
} 

public static int getScreenWidth() { 
    return Resources.getSystem().getDisplayMetrics().widthPixels; 
} 
} 

我希望我的回答能幫助別人。