微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在android中显示来自url的图像

我查看了互联网,但未能找到如何从网址显示图像的工作示例.

以下代码崩溃,我无法找到原因..非常感谢任何帮助.谢谢.

TesteImages.java:

package pac.image3;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class Testimages extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        ImageView image = (ImageView) findViewById(R.id.test_image);

        String imageUrl = "http://www.small-world.net/_borders/small_world_logo.gif";
        try {
          ImageView i = (ImageView)findViewById(R.id.test_image);
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
          i.setimageBitmap(bitmap);
          setContentView(image);
        } catch (MalformedURLException e) {
          e.printstacktrace();
        } catch (IOException e) {
          e.printstacktrace();
        }


    }
}

RES /布局/ main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />

    <ImageView 
   android:id="@+id/test_image"
   android:src="@drawable/icon"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   />

</LinearLayout>

解决方法:

只需使用以下方法从url中绘制图像:

Drawable drawable_from_url(String url, String src_name) throws 
   java.net.MalformedURLException, java.io.IOException 
{
   return Drawable.createFromStream(((java.io.InputStream)
      new java.net.URL(url).awagetContent()), src_name);
}

只需将字符串url传递给方法(并为src_name传递任何字符串),它将返回一个可绘制对象,然后使用imageview的setBckgroundDrawable()方法设置图像的背景.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐