Java-android使用GridView布局的电子相册&服务器获取图片
转 http://www.tuicool.com/articles/B7JNv2
电子相册的思路:
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;
} }
}
下面这个类就是点击任意一张图片,开启意图Intent,Create另一个Activity,就是单独一个图片的页面
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>
ProgressBar是加载数据时的一个加载效果
Java-android使用GridView布局的电子相册&服务器获取图片的更多相关文章
- java如何从一段html代码中获取图片的src路径
java如何从一段html代码中获取图片的src路径 package com.cellstrain.icell.Test; import java.util.ArrayList;import java ...
- [Android] 通过GridView仿微信动态添加本地图片
原文:http://blog.csdn.net/eastmount/article/details/41808179 前面文章讲述的都是"随手拍"中图像处理的操作,此篇文章主要讲述 ...
- Java不需要加载整张图片而获取图片的大小
转载地址 http://blog.jdk5.com/zh/java-get-image-size-without-loading-the-whole-data/ 利用Java类,获取图片的类型,宽度和 ...
- Android获取本地相册图片、拍照获取图片
需求:从本地相册找图片,或通过调用系统相机拍照得到图片. 容易出错的地方: 1,当我们指定了照片的uri路径,我们就不能通过data.getData();来获取uri,而应该直接拿到uri(用全局变量 ...
- android 照相或从相册获取图片并裁剪
照相或从相册获取图片并裁剪 在android应用中很多时候都要获取图片(例如获取用户的头像)就需要从用户手机上获取图片.可以直接照,也可以从用户SD卡上获取图片,但获取到的图片未必能达到要求.所以要对 ...
- Atitit.嵌入式web 服务器 java android最佳实践
Atitit.嵌入式web 服务器 java android最佳实践 1. Android4.4.21 2. 自己的webserver1 3. CyberHTTP for Java cybergar ...
- Android中GridView通过自定义适配器(未优化)实现图文视图排列
Android中GridView组件用来以网格方式排列视图,与矩阵类似,当屏幕上有很多元素(文字.图片或其他元素)需要显示时,可以使用该组件.下面我们通过代码实现如下图例(为了方便截图,将事件处理(土 ...
- GridView布局,自定义适配器,水平滚动
添加GridItem布局XML文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout ...
- Android中GridView拖拽的效果【android进化三十六】
最 近看到联想,摩托罗拉等,手机launcher中有个效果,进入mainmenu后,里面的应用程序的图标可以拖来拖去,所以我也参照网上给的代码,写了 一个例子.还是很有趣的,实现的流畅度没有人家的 ...
随机推荐
- 【MYSQL建库和建表】MYSQL建库和建表
1.Navicat创建Mysql数据库 2.创建创建用户表和索引 CREATE TABLE `t_user` ( `id` ) NOT NULL AUTO_INCREMENT COMMENT '主键' ...
- 鸡汤 - Choice is yours
传送门 https://kamranahmed.info/blog/2018/03/24/choice-is-yours/ Our whole lives are driven by the choi ...
- python 切片技巧
说明: 字符串[开始索引:结束索引:步长] 开始索引:从指定位置开始截取: 结束索引:从指定位置结束截取,但不包含该位置的字符. 步长:不指定时步长为1: 1)当步长为正数时候,那么切片是从左到右进行 ...
- uWSGI配置参数释义
uWSGI配置参数释义 socket : 地址和端口号,例如:socket = 127.0.0.1:50000 processes : 开启的进程数量 workers : 开启的进程数量,等同于pro ...
- ConcurrentHashMap 结构 1.7 与1.8
1.结构 1.7 segment+HashEntity+Unsafe 1.8 移除Segment,使锁的粒度更小,Synchronized+CAS+Node+Unsafe 2. put() 1.7 先 ...
- query_phase_execution_exception
ES报错信息: { "error": { "root_cause": [ { "type": "query_phase_execu ...
- 九、web.xml理解
1.web.xml文件在每个web工程不是必须要有的: web.xml文件是用来初始化配置信息:比如Welcome页面.servlet.servlet-mapping.filter.liste ...
- iOS 10.3 以上系统实现应用内评分及开发者回复评论
在 iOS 10.3 之前,如果你要给一个应用评分,那么你需要打开 App Store,搜索应用,找到评论,点击撰写评论,然后评分.整个评分流程非常繁琐,还要忍受漫长的页面加载,导致很少有用户愿意主动 ...
- 获取Linux系统运行情况信息
代码: #include <stdio.h> #include <unistd.h> /* usleep() */ #include <stdlib.h> #inc ...
- 如果你是新晋的leader, 你可能需要了解这些。
背景 在职业发展的道路上,我们总会面临这样的抉择: 是在技术的路上一条路走到黑,做技术专家 接触管理, 走上管理 年龄大了,搬砖没人要,转型 or 去公司楼下卖炒粉 我曾经有个小小的愿望: 在毕业5年 ...