2013-07-12 30 views
4

我想從url下載圖像並將其設置爲運行時在操作欄中的主圖標。我正在使用AsyncTask來執行它,但它似乎沒有改變它。有任何想法嗎?從url設置位圖作爲操作欄主頁圖標在Android中

class getProfilePicture extends AsyncTask<Void, Void, Void> { 

     protected Void doInBackground(Void... params) { 
      try { 
       URL url; 
       url = new URL("http://www.i2clipart.com/cliparts/2/a/3/2/clipart-fcrc-logo-handshake-2a32.png"); 
       HttpURLConnection conn = (HttpURLConnection) url 
         .openConnection(); 
       conn.setDoInput(true); 
       conn.connect(); 
       InputStream is = conn.getInputStream(); 
       image = BitmapFactory.decodeStream(is); 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      return null; 

     } 

    protected void onPostExecute() { 
     // TODO: check this.exception 
     Resources res = getResources(); 
     BitmapDrawable icon = new BitmapDrawable(res, image); 
     getSupportActionBar().setIcon(icon); 
     //getSupportActionBar().setLogo(icon); 
     } 
    } 

回答

0

你可以試試這個科特林代碼

Glide.with(this).load(imageUrl).asBitmap().into(object : SimpleTarget<Bitmap>() { 
        override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) { 
         val drawable = BitmapDrawable(resources, resource) 
         supportActionBar?.setIcon(drawable) 
        } 
       })