这个案例呢,主要是让你学会ImageSwitcher的使用,以及怎么网络获取图片
不多说,直接代码:
先看效果:
MainActivity.java源码:
package com.example.photos; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher.ViewFactory; /** * 2013-6-25 下午8:52:17 * * @author 乔晓松 */ @SuppressLint("HandlerLeak") @SuppressWarnings("deprecation") public class MainActivity extends Activity implements ViewFactory, OnItemSelectedListener { protected static final int DATAS = 0; public ImageSwitcher imageSwitcher; public Gallery gallery; private List<String> list; public String basePath = "http://172.22.64.6:8080/lession08_image/images/"; public List<Map<String, Object>> datas; public Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = new ArrayList<String>(); datas = new ArrayList<Map<String, Object>>(); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case DATAS: // 设置适配器 gallery.setAdapter(new ImageAdapter(MainActivity.this)); break; default: break; } } }; // 开启线程访问网络,获取数据 new Thread(new Runnable() { @Override public void run() { list = HttpClientTool .httpClientJSON("http://172.22.64.6:8080/lession08_image/csdn/ImagesAction_httpAllImages.action"); if (list != null) { // 获取图片,并添加到集合中 for (int i = 0; i < list.size(); i++) { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> bitmap = HttpClientTool.send( MainActivity.this, basePath + list.get(i)); if (map != null) { map.put("img", (Bitmap) (bitmap.get("img"))); map.put("name", list.get(i)); datas.add(map); } } } handler.sendEmptyMessage(DATAS); } }).start(); // 获取视图 imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher1); gallery = (Gallery) findViewById(R.id.gallery); // 设置当前的工厂 imageSwitcher.setFactory(this); // 设置切换的动画 imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); // 设置选中的事件 gallery.setOnItemSelectedListener(this); } // 设置View视图 @Override public View makeView() { ImageView i = new ImageView(this); i.setBackgroundColor(0xFF000000); i.setScaleType(ImageView.ScaleType.FIT_CENTER); i.setLayoutParams(new ImageSwitcher.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return i; } // 选中的图片 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Bitmap bitmap = (Bitmap) datas.get(position).get("img"); BitmapDrawable bd = new BitmapDrawable(bitmap); imageSwitcher.setImageDrawable(bd); } public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } // 适配器 public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return list.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { // 自己创建一个ImageView视图 ImageView i = new ImageView(mContext); // 设置ImageView视图的资源 i.setImageBitmap((Bitmap) datas.get(position).get("img")); i.setAdjustViewBounds(true); // 设置ImageView的布局参数 i.setLayoutParams(new Gallery.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // i.setBackgroundResource(R.drawable.ic_launcher); return i; } } }
工具类源码:
package com.example.photos; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import android.widget.Toast; /** * 2013-6-19 下午2:41:46 * * @author 乔晓松 */ public class HttpClientTool { public static String sendHttpGet(String path) { // System.out.println(path + "-----"); try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(path); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStream is = httpResponse.getEntity().getContent(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len = 0; while ((len = is.read(buff)) != -1) { bos.write(buff, 0, len); } byte[] data = bos.toByteArray(); String content = new String(data); bos.flush(); bos.close(); is.close(); return content; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } // 网络获取图片 @SuppressWarnings("unused") public static Bitmap send(Context context, String path, String id) { // System.out.println(path + "-----网络获取图片"); Bitmap bitmap = null; try { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(5000); if (httpURLConnection.getResponseCode() == 200) { if (bitmap != null) { bitmap.recycle(); System.gc(); } // 获取输入流对象 InputStream is = httpURLConnection.getInputStream(); // 获取Bitmap对象 bitmap = BitmapFactory.decodeStream(is); // 得到图片的名称 String imgName = id + "_" + path.substring(path.lastIndexOf("/") + 1); // 获取图片存放的路径 // String str = Environment.getExternalStorageDirectory() // .getPath() + "/video/" + imgName; String str = context.getFilesDir() + "/" + imgName; // 实例化此路径的文件 File file = new File(str); // 判断此图片文件是否存在,不存在就执行下载 // System.out.println(!file.exists()); // synchronized (context) { if (!file.exists()) { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(path); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream in = httpResponse.getEntity().getContent(); // FileOutputStream fos = new FileOutputStream(file);// // context.openFileOutput(name, // mode) FileOutputStream fos = context.openFileOutput(imgName, Context.MODE_PRIVATE); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) > 0) { fos.write(buffer, 0, len); } // fos.flush(); fos.close(); in.close(); } // } } else { Toast.makeText(context, "服务器端响应错误", Toast.LENGTH_LONG).show(); } httpURLConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; } // 从sdcard获取图片 public static Bitmap sendLocalBitmap(Context context, String path) { System.out.println(path + "----------sdcard获取图片"); Bitmap bitmap = null; try { File file = new File(path); FileInputStream fis = new FileInputStream(file); bitmap = BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } return bitmap; } // 获取服务器端images文件下的所有图片名称 public static List<String> httpClientJSON(String path) { List<String> list = null; try { list = new ArrayList<String>(); HttpGet httpGet = new HttpGet(path); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { StringBuilder builder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity() .getContent())); String str = null; while ((str = bufferedReader.readLine()) != null) { builder.append(str); } JSONObject jsonObject = new JSONObject(builder.toString()); JSONArray jsonArray = jsonObject.getJSONArray("list"); for (int i = 0; i < jsonArray.length(); i++) { Object obj = jsonArray.opt(i); list.add(obj.toString()); // System.out.println(obj.toString()); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return list; } @SuppressWarnings("unused") @SuppressLint("NewApi") public static Map<String, Object> send(Context context, String path) { Map<String, Object> map = new HashMap<String, Object>(); ImageView imageView = null; imageView = new ImageView(context); imageView.setMaxHeight(100); imageView.setMaxWidth(100); Bitmap bitmap = null; try { URL url = new URL(path); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setConnectTimeout(5000); if (httpURLConnection.getResponseCode() == 200) { if (bitmap != null) { // System.out.println("---" + bitmap); bitmap.recycle(); System.gc(); } InputStream is = httpURLConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(is); // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inSampleSize = computeSampleSize(options, -1, // 128*128); // options.inJustDecodeBounds = true; int length = httpURLConnection.getContentLength(); // System.out.println(httpURLConnection.get); // MediaStore map.put("img", bitmap); map.put("length", length); } else { Toast.makeText(context, "服务器端响应错误", Toast.LENGTH_LONG).show(); } httpURLConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return map; } }
布局文件的源码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ImageSwitcher android:id="@+id/imageSwitcher1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" > </ImageSwitcher> <Gallery android:id="@+id/gallery" android:layout_width="match_parent" android:layout_height="60dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:background="#55000000" android:gravity="center_vertical" android:spacing="16dp" /> </RelativeLayout>
当然,这个应用也是需要授网络的权限的额
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
功能没什么,正在进一步的完善和添加新的功能