Android 显示来自外部源的图像按钮

Android 显示来自外部源的图像按钮,android,imagebutton,Android,Imagebutton,我正在做一个项目,我需要显示一些保存在sd卡或Url中的图像按钮。我该怎么做?或者最佳实践是什么? 其目的是仅更换sd卡中的文件即可更改按钮上的图像。 如果我不知道将来会显示哪些图像,还有其他解决方案吗? THX以下是如何将图像从URL加载到可绘制对象中: InputStream is = (InputStream) new URL("http://my.url/path/to/image").getContent(); Drawable buttonBg = Drawable.createFr

我正在做一个项目,我需要显示一些保存在sd卡或Url中的图像按钮。我该怎么做?或者最佳实践是什么? 其目的是仅更换sd卡中的文件即可更改按钮上的图像。 如果我不知道将来会显示哪些图像,还有其他解决方案吗?
THX

以下是如何将图像从URL加载到可绘制对象中:

InputStream is = (InputStream) new URL("http://my.url/path/to/image").getContent();
Drawable buttonBg = Drawable.createFromStream(is, null);
然后将其设置为背景:

button.setBackgroundDrawable(buttonBg);
或API 16+使用:

button.setBackground(buttonBg);
如果要读取文件,请使用FileInputStream,如下所示:

FileInputStream fis = openFileInput("/my/path/to/image"); 
Drawable buttonBg= Drawable.createFromStream(fis, null);
@卡梅克斯 已解决:


Thx很多。

我有一些问题…如果我用try/catch环绕输入流url(否则我会出错),get createFromStream变量未初始化。。。我尝试初始化,但午餐时应用程序崩溃。。。


    ImageButton box1 = (ImageButton)findViewById(R.id.box1);
    Drawable drawable = GetImg("path/to/image.jpg"); 
    box1.setBackground(drawable); 


    private Drawable GetImg(String url) 
    { 
     try 
     { 
      InputStream is = (InputStream) new URL(url).getContent(); 
      Drawable d = Drawable.createFromStream(is, "src name"); 
      return d; 
     }
     catch (Exception e) 
    { 
    System.out.println("Err="+e); return null; 
    } 
    }