2013-03-04 82 views
0

我有一個圖像按鈕,並希望從互聯網URL設置背景圖像。我不想將背景圖片保存到SD卡,而是我的圖像按鈕的圖像需要URL。我怎樣才能做到這在Android中如何在Android中設置網頁圖片按鈕資源?

+0

你需要將它下載到一個位圖變量,然後將其設置爲背景圖片。 Android不是您想要實現的功能的瀏覽器。 – abbath 2013-03-04 11:15:52

+0

我認爲你的答案就在這裏 http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android – 2013-03-04 11:24:19

+0

@MudassarShaheen我覺得一個評論是不夠的同樣的鏈接:) – 2013-03-04 12:22:45

回答

0

從未嘗試過這一點,但完全希望這將與您

private Drawable ImageOperations(Context ctx, String url, String saveFilename) { 
    try { 
     InputStream is = (InputStream) this.fetch(url); 
     Drawable d = Drawable.createFromStream(is, saveFilename); 
     return d; 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
     return null; 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

和圖像視圖

ImageView IV= (ImageView)findViewById(R.id.imageId);  
Drawable drw = ImageOperations(this,url,filename) 
IV.setBackgroundDrawable(drw) 

獲取URL

public Object fetch(String address) throws MalformedURLException,IOException { 

    URL url = new URL(address); 
    Object content = url.getContent(); 
    return content; 
} 
0

嘗試工作這

 Bitmap bitmap; 
class loadImage extends AsyncTask<Void , Void, Void>{ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 
    @Override 
    protected Void doInBackground(Void... params) { 
     URL url = new URL(stringURL); 
     URI uri = new URI(url.getProtocol(), url.getHost(), 
       url.getPath(), url.getQuery(), null); 
     HttpURLConnection connection = (HttpURLConnection) uri 
       .toURL().openConnection(); 
     connection.setDoInput(true); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); 

     int bufferSize = 1024; 
     byte[] buffer = new byte[bufferSize]; 
     int len = 0; 
     while ((len = input.read(buffer)) != -1) { 
      byteBuffer.write(buffer, 0, len); 
     } 
     byte[] img = byteBuffer.toByteArray(); 
     byteBuffer.flush(); 
     byteBuffer.close(); 
     input.close(); 
     bitmap = BitmapFactory.decodeByteArray(img, 0, img.length); 
     return null; 
    } 
    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     ImageButton image_btn = (ImageButton)findViewById(R.id.your_image_button_id); 
     image_btn.setImageBitmap(bitmap); 
    } 
}