电子相册的思路:
1.先是考虑布局,我用的是GridView布局
2.GridView中又该怎么显示图片,其实我的这个应用每个图片都是同一个布局,首先要实现适配器接口,再利用充气泵LayoutInflater把布局文件转换成View视图对象
3.怎么从服务器获取图片,又是怎么捉去到的
有思路不等于你会了,直接给你上代码吧:
首先介绍下我的应用的功能:
1.显示的每一张图片,点击后都可以显示出单独的一张,并且是全屏
2.如果点击其中的任意一张图片长时间,会弹出窗口,显示这张图片的基本的信息
不足:
1.现在存在获取资源过多,内存溢出的bug,后期我会处理,可以选择把图片保存到本地,不全部从服务器获取
2.功能不够强大,我还会用另一个布局,把电子相册的效果呈现处理
先看效果再看代码啊
MainActivity.java源码:
package com.example.photo; 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.app.AlertDialog; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; /** * 2013-6-15 下午12:54:56 * * @author 乔晓松 */ public class MainActivity extends Activity { protected static final int TEXT = 0; protected static final int ACTIVITY = 1; public GridView gridView; public int id; public Handler handler; public static Object[] path; // = { "span.jpg", "span1.jpg", "span2.jpg", // "span3.jpeg", "psb.jpeg", "psbpan.jpeg" // }; public String basePath = "http://172.22.64.6:8080/lession08_image/images/"; public List<Map<String, Object>> datas; public LayoutInflater inflater; public Map<String, Integer> fileMap; public ProgressBar progressBar; @SuppressLint({ "HandlerLeak", "CutPasteId" }) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = (GridView) findViewById(R.id.gridView1); progressBar = (ProgressBar) findViewById(R.id.progressBar1); progressBar.setVisibility(View.VISIBLE); inflater = (LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE); datas = new ArrayList<Map<String, Object>>(); fileMap = new HashMap<String, Integer>(); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case TEXT: progressBar.setVisibility(View.GONE); gridView.setAdapter(new MyListAdapter()); break; default: break; } } }; new Thread(new Runnable() { @Override public void run() { List<String> list = HttpClientTool .httpClientJSON("http://172.22.64.6:8080/lession08_image/csdn/ImagesAction_httpAllImages.action"); if (list != null) { path = list.toArray(); } for (int i = 0; i < path.length; i++) { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> bitmap = HttpClientTool.send( MainActivity.this, basePath + path[i]); if (map != null) { map.put("img", (Bitmap) (bitmap.get("img"))); map.put("name", path[i]); datas.add(map); } fileMap.put(path[i].toString(), (Integer) (bitmap.get("length"))); } handler.sendEmptyMessage(TEXT); } }).start(); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Integer length = fileMap.get(path[position]); Intent intent = new Intent(MainActivity.this, ImageActivity.class); intent.putExtra("id", position); intent.putExtra("basepath", basePath); intent.putExtra("path", path); intent.putExtra("length", length); startActivity(intent); } }); gridView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { Integer length = fileMap.get(path[position]); new AlertDialog.Builder(MainActivity.this) .setTitle("图片信息") .setMessage( "图片名称:" + path[position] + "\n图片大小:" + length + "k").show(); return false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } class MyListAdapter extends BaseAdapter { @Override public int getCount() { return datas.size(); } @Override public Object getItem(int position) { return datas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = inflater.inflate(R.layout.grid_item, null); ImageView tx_name = (ImageView) v.findViewById(R.id.ItemImage); TextView tx_phone = (TextView) v.findViewById(R.id.ItemText); Map<String, Object> map = datas.get(position); tx_name.setImageBitmap((Bitmap) map.get("img")); tx_phone.setText((String) map.get("name")); return v; } } }
package com.example.photo; import java.util.Map; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.widget.ImageView; import android.widget.RelativeLayout; /** * 2013-6-16 下午8:23:54 * * @author 乔晓松 */ public class ImageActivity extends Activity { public static final int IMG = 0; public Handler handler; public RelativeLayout relativeLayout = null; public ImageView imageView; public int length; public int id; public Object[] path; @SuppressLint({ "HandlerLeak", "NewApi" }) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case IMG: if (relativeLayout != null) { ImageActivity.this.setContentView(relativeLayout); } break; default: break; } } }; new Thread(new Runnable() { @Override public void run() { Intent intent = ImageActivity.this.getIntent(); Bundle bundle = intent.getExtras(); id = bundle.getInt("id"); length = bundle.getInt("length"); String basePath = bundle.getString("basepath"); path = (Object[]) bundle.get("path"); relativeLayout = new RelativeLayout(ImageActivity.this); imageView = new ImageView(ImageActivity.this); Map<String, Object> bitmap = HttpClientTool.send( ImageActivity.this, basePath + path[id].toString()); imageView.setImageBitmap((Bitmap) bitmap.get("img")); imageView.setMaxWidth(300); imageView.setMaxHeight(400); relativeLayout.addView(imageView); handler.sendEmptyMessage(IMG); } }).start(); /* * imageView.setOnLongClickListener(new OnLongClickListener() { * * @Override public boolean onLongClick(View v) { // new * AlertDialog.Builder * (ImageActivity.this).setTitle("图片信息").setMessage("图片名称:" * +path[id]+"\n\t图片大小:"+length+"k").show(); return false; } }); */ } @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } }
下面的这个类是我自己写的一个工具类,用户发送请求或者获取图片
package com.example.photo; import java.io.BufferedReader; 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 上午9:44:41 * * @author 乔晓松 */ public class HttpClientTool { // 获取图片以及图片的信息 @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; } public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } public static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math .sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == -1) && (minSideLength == -1)) { return 1; } else if (minSideLength == -1) { return lowerBound; } else { return upperBound; } } // 获取服务器端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; } } //
这么多代码写出来了,要是没有授权还是不行的,必须有网络权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/>
GridView布局
<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" > <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="160dp" /> <GridView android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:numColumns="3" tools:ignore="AdapterViewChildren,UselessParent" > </GridView> </RelativeLayout>
单个图片的布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="4dip" > <ImageView android:id="@+id/ItemImage" android:layout_width="85dp" android:layout_height="85dp" android:layout_centerHorizontal="true" tools:ignore="ContentDescription" > </ImageView> <TextView android:id="@+id/ItemText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/ItemImage" android:layout_centerHorizontal="true" > </TextView> </RelativeLayout>
如有什么错误或疑问,请留言或发送邮件致我