2012-07-10 39 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

相关问题