|
您好: 您的問題應該是 Imageview 如何載入 SDCARD 或 url 的圖檔,這裡有一篇利用 AsyncTask 非同步載入 url 圖檔,您可以參考。 http://stackoverflow.com/questions/41519292/how-to-load-image-from-web-in-imageviewmain-activity-for-an-app
附我們測試的範例。<ListView_URL.rar> 請由這個網址下載。 https://www.dropbox.com/s/n6kx0hpw8mo6riz/ListView_URL.rar?dl=0
// 主要程式碼 public class MainActivity extends AppCompatActivity { ListView lstPrefer; // int[] resIds = new int[]{ R.drawable.basketball, R.drawable.football,R.drawable.baseball, R.drawable.other}; // 不用了 String[] Balls= new String[] {"籃球","足球","棒球","其他"}; String[] engNames = { "Basket Ball", "Foot Ball","Base Ball","Other"};
String[] urls = { "basketball", "football","baseball","other"}; // 新加入模擬取得 SQLite 的資料 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// 取得介面元件 lstPrefer=(ListView)findViewById(R.id.lstPrefer);
// 建立自訂的 Adapter MyAdapter adapter=new MyAdapter(this);
// 設定 ListView 的資料來源 lstPrefer.setAdapter(adapter); }
public class MyAdapter extends BaseAdapter { private LayoutInflater myInflater; public MyAdapter(Context c){ myInflater = LayoutInflater.from(c); } @Override public int getCount(){ return Balls.length; } @Override public Object getItem(int position){ return Balls[position]; } @Override public long getItemId(int position){ return position; } @Override public View getView(int position, View convertView, ViewGroup parent){ convertView = myInflater.inflate(R.layout.mylayout, null);
// 取得 mylayout.xml 中的元件 ImageView imgLogo = (ImageView) convertView.findViewById(R.id.imgLogo); TextView txtName = ((TextView) convertView.findViewById(R.id.txtName)); TextView txtengName = ((TextView) convertView.findViewById(R.id.txtengName));
// 設定元件內容 // imgLogo.setImageResource(resIds[position]); // 原來這一行不用了 // 改為連結 url 檔案 new DownloadImageTask(imgLogo).execute("http://www.android-examples.com/wp-content/uploads/2016/03/demo_image.jpg");
// 這是我用本機測試 // String url="http://192.168.0.101/exIntent04/drawable/" + urls[position] + ".png"; // new DownloadImageTask(imgLogo).execute(url);
txtName.setText(Balls[position]); //或 txtName.setText(""+getItem(position)); txtengName.setText(engNames[position]);
return convertView; } }
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; }
protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { // Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; }
protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } }
}
|