| 代碼如下 |
複製代碼 |
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myimage); ImageView image1 = (ImageView) findViewById(R.myImage.image); //Bitmap bitmap = getLoacalBitmap("/aa/aa.jpg"); //從本地取圖片 Bitmap bitmap = getHttpBitmap("hpath.jpg"); //從網上取圖片 image1 .setImageBitmap(bitmap); //設定Bitmap }
/** * 載入本地圖片 * http://www.111cn.net * @param url * @return */ public static Bitmap getLoacalBitmap(String url) { try { FileInputStream fis = new FileInputStream(url); return BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } /** * 從伺服器取圖片 *http://www.111cn.net * @param url * @return */ public static Bitmap getHttpBitmap(String url) { URL myFileUrl = null; Bitmap bitmap = null; try { Log.d(TAG, url); myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setConnectTimeout(0); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } |
ImageView 無法setImageBitmap,不顯示圖片解決辦法
以下是handler
| 代碼如下 |
複製代碼 |
handler.post(new Runnable() { @Override public void run() { playAdver(); } });
|
以下是playAdver()方法,主要是顯示圖片
| 代碼如下 |
複製代碼 |
private void playAdver() { for (int i = 0; i < advertisementsList.size(); i++) { advertisement = advertisementsList.get(i); fileName = advertisement.getName(); index = advertisement.getName().indexOf("."); String postfix = fileName.substring(index, fileName.length()); time = advertisement.getTime() * 100; if (postfix.compareToIgnoreCase(".jpg") == 0 || postfix.compareToIgnoreCase(".png") == 0) { adverImage.setVisibility(View.VISIBLE); adverImage.setImageBitmap(BitmapFactory.decodeFile(fileName)); try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
執行了adverImage.setImageBitmap(BitmapFactory.decodeFile(fileName));但是在真機上不現實圖片,為什嗎?
因為我是在主線程裡面執行的,故不會顯示,以解決