【问题标题】:How to display an image from an URL within textView如何在 textView 中显示来自 URL 的图像
【发布时间】:2011-12-11 14:00:31
【问题描述】:

我有一个文本视图。在我的代码中,我在其中添加了一些文本行。我还想在这些行之间显示来自外部 URL(而不是来自我的资源文件夹)的一些图像。每件事都是动态的,即生成的文本和图像 URL 将在流程中生成。所以我必须通过我的代码获取图像并添加它。

想知道是否有办法在文本视图中从外部 URL 插入图像?也欢迎任何更好的方法。

【问题讨论】:

    标签: android android-imageview android-image


    【解决方案1】:

    您必须将它与 asynctask 一起使用, 在doInbackground() 中打开连接 在onPostExecute()中将图片设置为textview

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

    希望对你有帮助

    【讨论】:

    • d.setId() 方法在我的项目中不可用。
    【解决方案2】:

    您可能想要使用异步任务来获取图像。这将在您的其他任务的后台运行。您的代码可能如下所示:

        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...
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-26
      • 2020-06-25
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多