How to display an image from an URL within textView

烈酒焚心 提交于 2019-11-28 05:40:39

问题


I have a textView. In my code I am adding some lines of text in it. I also want to display some image from an external URL (not from my resource folder) just in between those lines. Every thing is dynamic i.e. the text generated and the image URL will be generated on the flow.So i have to fetch the image through my code and add it.

Wondering if there is a way to insert images from external URL within text view? Also any better approach is always welcome.


回答1:


You will have to use this along with asynctask, open connection in doInbackground() set image to textview in onPostExecute()

  try {
        /* Open a new URL and get the InputStream to load data from it. */
        URL aURL = new URL("ur Image URL");
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        /* Buffered is always good for a performance plus. */
        BufferedInputStream bis = new BufferedInputStream(is);
        /* Decode url-data to a bitmap. */
        Bitmap bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();

        Drawable d =new BitmapDrawable(bm);
       d.setId("1");
 textview.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);// wherever u want the image relative to textview
        } catch (IOException e) {
        Log.e("DEBUGTAG", "Remote Image Exception", e);
        } 

hope it helps




回答2:


You are going to probably want to use an asynctask to grab the image. This will run in the background from your other tasks. Your code may look something like this:

    public class ImageDownloader extends AsyncTask<String, Integer, Bitmap>{

    private String url;
    private final WeakReference<ImageView> imageViewReference;

    //a reference to your imageview that you are going to load the image to
    public ImageDownloader(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... arg0) {
        if(isCancelled())
            return null;
        Bitmap retVal;

        url = arg0[0];//this is the url for the desired image
        ...download your image here using httpclient or another networking protocol..
        return retVal;
    }
    @Override
    protected void onPostExecute(Bitmap result) {
        if (isCancelled()) {
            result = null;
            return;
        }
        ImageView imageView = imageViewReference.get();
        imageView.setImageBitmap(result);
    }
    @Override
    protected void onPreExecute() {
        ...do any preloading you might need, loading animation, etc...
    }


来源:https://stackoverflow.com/questions/8464506/how-to-display-an-image-from-an-url-within-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!