1. 程式人生 > >android imageView 獲取指定名字的圖片、從MyEclipse伺服器下載圖片

android imageView 獲取指定名字的圖片、從MyEclipse伺服器下載圖片

設定指定名字的圖片;

int imgId = getResources().getIdentifier(imgName, "drawable", getPackageName());   //imgName為圖片名稱;
imageView.setImageResource(imgId);

所以當有一組圖片要顯示時(圖片以a1、a2、a3……命名)可以用for迴圈:

int[] imgs = new int[7];
for(int i=0; i<imgs.size(); i++)
{
    imgs[i] = getResources().getIdentifier("a"+i, "drawable"
, getPackageName()); }

從MyEclipse伺服器上下載圖片;

    private Bitmap getImage(String imgPath)
    {
        URL url = null;
        Bitmap bitmap = null;
        InputStream input = null;
        HttpURLConnection httpCon = null;
        //伺服器地址+專案名+圖片的路徑;http://192.168.18.145:8080/Order/images/a.png (images/a.png是在伺服器的WebRoot資料夾下);
url = new URL(Content.path + imgPath); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setConnectTimeout(5000); //設定超時時間; System.out.println("============="); if(httpCon.getResponseCode() == 200) { System.out.println("----------="
); input = httpCon.getInputStream(); bitmap = BitmapFactory.decodeStream(input); System.out.println("=====" + bitmap); } //獲取失敗的話,就顯示本地的任意一張圖片; else { bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.dish_no_image); } if(input != null) { input.close(); } if(httpCon != null) { httpCon.disconnect(); } return bitmap; }