2012-07-10 40 views
2

我試圖從存儲在SD卡上的Png文件創建一個位圖,然後在imageView中設置該位圖。 但它不工作。從存儲在sdcard中的png文件創建一個位圖(Android)

下面的代碼:

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 

import com.pxr.tutorial.xmltest.R; 

import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Environment; 
import android.widget.ImageView; 

public class Getbackground { 
    URL url; 

    public static long downloadFile(URL url2) { 
    try { 

     URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png"); 
     InputStream input = url.openStream();{ 
     try { 

      File fileOnSD=Environment.getExternalStorageDirectory();  
      String storagePath = fileOnSD.getAbsolutePath(); 
      OutputStream output = new FileOutputStream (storagePath + "/oranjelanbg.png"); 
       try { 

        byte[] buffer = new byte[1024]; 
        int bytesRead = 0; 
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
        output.write(buffer, 0, bytesRead); 
        } 
        } finally { 
      output.flush(); 
      output.close(); 
//---------------------------------------------------------------------------------------------------------- 
      Bitmap BckGrnd = BitmapFactory.decodeFile(storagePath + "/oranjelanbg.png"); 
      ImageView BackGround=(ImageView)findViewById(R.id.imageView1); 
      BackGround.setImageBitmap(BckGrnd); 
//----------------------------------------------------------=----------------------------------------------- 
      } 
      } catch (IOException e) { 
      throw new RuntimeException(e); 
    } finally { 
     try { 
      input.close(); 
      } catch (IOException e) { 
      throw new RuntimeException(e); 
    } 
    }  
}  
     } catch (MalformedURLException ex) { 
     throw new RuntimeException(ex); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 

     return 0; 
    } 
//----------------------------------------------------------------------------------------- 
    private static ImageView findViewById(int imageview1) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
//----------------------------------------------------------------------------------------- 
} 

該文件確實在SD卡上加載成功地,但我不能似乎得到在視圖中IMG。

+0

嗯似乎並沒有解決問題。 – 2012-07-10 10:51:37

回答

1

你不能..

ImageView BackGround=(ImageView)findViewById(R.id.imageView1); 
BackGround.setImageBitmap(BckGrnd); 

你怎麼能得到的ImageView非活性類Getbackground參考?

您只能在MainUI線程中更新UI組件,並且它在非Activity類中只使用該調用活動類的引用(Context)。

因此,在Getbackground完成後,將此代碼放入Activity類中。

+0

是的!謝謝!它現在正在工作! – 2012-07-10 11:05:06

+0

歡迎夥伴..!快樂編碼..! – user370305 2012-07-10 11:06:12

+0

@ user370305你說過__如何在非活動類Getbackground中獲得ImageView的引用?__但是如果我們傳遞上下文並將imageview引用更新到'Getbackground'構造函數,那麼這將是可能的。我對嗎 ?對於圖片的延遲加載,我們通常會這樣做。 – sunil 2012-07-10 11:09:06

相關問題