仿照微信,朋友圈分享图片功能 。可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 。很不错的源码,大家有需要可以下载看看 。
下载地址 : 微信上传图片源码
很多网友不知道怎么获取图片路径,这里贴出来:
String path = Bimp.tempSelectBitmap.get(position).getImagePath();
//部分代码如下
- package com.king.photo.activity;
- import android.annotation.SuppressLint;
- import android.app.Activity;
- import android.content.Context;
- import android.content.Intent;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.graphics.Color;
- import android.graphics.drawable.BitmapDrawable;
- import android.graphics.drawable.ColorDrawable;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.provider.MediaStore;
- import android.util.Log;
- import android.view.Gravity;
- import android.view.KeyEvent;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.ViewGroup;
- import android.view.ViewGroup.LayoutParams;
- import android.view.animation.AnimationUtils;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.BaseAdapter;
- import android.widget.Button;
- import android.widget.GridView;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.PopupWindow;
- import android.widget.RelativeLayout;
- import com.king.photo.R;
- import com.king.photo.util.Bimp;
- import com.king.photo.util.FileUtils;
- import com.king.photo.util.ImageItem;
- import com.king.photo.util.PublicWay;
- import com.king.photo.util.Res;
- //首页面activity
- public class MainActivity extends Activity {
- private GridView noScrollgridview;
- private GridAdapter adapter;
- private View parentView;
- private PopupWindow pop = null;
- private LinearLayout ll_popup;
- public static Bitmap bimap ;
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Res.init(this);
- bimap = BitmapFactory.decodeResource(
- getResources(),
- R.drawable.icon_addpic_unfocused);
- PublicWay.activityList.add(this);
- parentView = getLayoutInflater().inflate(R.layout.activity_selectimg, null);
- setContentView(parentView);
- Init();
- }
- public void Init() {
- pop = new PopupWindow(MainActivity.this);
- View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
- ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
- pop.setWidth(LayoutParams.MATCH_PARENT);
- pop.setHeight(LayoutParams.WRAP_CONTENT);
- pop.setBackgroundDrawable(new BitmapDrawable());
- pop.setFocusable(true);
- pop.setOutsideTouchable(true);
- pop.setContentView(view);
- RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
- Button bt1 = (Button) view
- .findViewById(R.id.item_popupwindows_camera);
- Button bt2 = (Button) view
- .findViewById(R.id.item_popupwindows_Photo);
- Button bt3 = (Button) view
- .findViewById(R.id.item_popupwindows_cancel);
- parent.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- pop.dismiss();
- ll_popup.clearAnimation();
- }
- });
- bt1.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- photo();
- pop.dismiss();
- ll_popup.clearAnimation();
- }
- });
- bt2.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- Intent intent = new Intent(MainActivity.this,
- AlbumActivity.class);
- startActivity(intent);
- overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
- pop.dismiss();
- ll_popup.clearAnimation();
- }
- });
- bt3.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- pop.dismiss();
- ll_popup.clearAnimation();
- }
- });
- noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
- noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
- adapter = new GridAdapter(this);
- adapter.update();
- noScrollgridview.setAdapter(adapter);
- noScrollgridview.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
- long arg3) {
- if (arg2 == Bimp.tempSelectBitmap.size()) {
- Log.i("ddddddd", "----------");
- ll_popup.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.activity_translate_in));
- pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
- } else {
- Intent intent = new Intent(MainActivity.this,
- GalleryActivity.class);
- intent.putExtra("position", "1");
- intent.putExtra("ID", arg2);
- startActivity(intent);
- }
- }
- });
- }
- @SuppressLint("HandlerLeak")
- public class GridAdapter extends BaseAdapter {
- private LayoutInflater inflater;
- private int selectedPosition = -1;
- private boolean shape;
- public boolean isShape() {
- return shape;
- }
- public void setShape(boolean shape) {
- this.shape = shape;
- }
- public GridAdapter(Context context) {
- inflater = LayoutInflater.from(context);
- }
- public void update() {
- loading();
- }
- public int getCount() {
- if(Bimp.tempSelectBitmap.size() == 9){
- return 9;
- }
- return (Bimp.tempSelectBitmap.size() + 1);
- }
- public Object getItem(int arg0) {
- return null;
- }
- public long getItemId(int arg0) {
- return 0;
- }
- public void setSelectedPosition(int position) {
- selectedPosition = position;
- }
- public int getSelectedPosition() {
- return selectedPosition;
- }
- public View getView(int position, View convertView, ViewGroup parent) {
- ViewHolder holder = null;
- if (convertView == null) {
- convertView = inflater.inflate(R.layout.item_published_grida,
- parent, false);
- holder = new ViewHolder();
- holder.image = (ImageView) convertView
- .findViewById(R.id.item_grida_image);
- convertView.setTag(holder);
- } else {
- holder = (ViewHolder) convertView.getTag();
- }
- if (position ==Bimp.tempSelectBitmap.size()) {
- holder.image.setImageBitmap(BitmapFactory.decodeResource(
- getResources(), R.drawable.icon_addpic_unfocused));
- if (position == 9) {
- holder.image.setVisibility(View.GONE);
- }
- } else {
- holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
- }
- return convertView;
- }
- public class ViewHolder {
- public ImageView image;
- }
- Handler handler = new Handler() {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- adapter.notifyDataSetChanged();
- break;
- }
- super.handleMessage(msg);
- }
- };
- public void loading() {
- new Thread(new Runnable() {
- public void run() {
- while (true) {
- if (Bimp.max == Bimp.tempSelectBitmap.size()) {
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- break;
- } else {
- Bimp.max += 1;
- Message message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- }
- }
- }
- }).start();
- }
- }
- public String getString(String s) {
- String path = null;
- if (s == null)
- return "";
- for (int i = s.length() - 1; i > 0; i++) {
- s.charAt(i);
- }
- return path;
- }
- protected void onRestart() {
- adapter.update();
- super.onRestart();
- }
- private static final int TAKE_PICTURE = 0x000001;
- public void photo() {
- Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- startActivityForResult(openCameraIntent, TAKE_PICTURE);
- }
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- switch (requestCode) {
- case TAKE_PICTURE:
- if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
- String fileName = String.valueOf(System.currentTimeMillis());
- Bitmap bm = (Bitmap) data.getExtras().get("data");
- FileUtils.saveBitmap(bm, fileName);
- ImageItem takePhoto = new ImageItem();
- takePhoto.setBitmap(bm);
- Bimp.tempSelectBitmap.add(takePhoto);
- }
- break;
- }
- }
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- for(int i=0;i<PublicWay.activityList.size();i++){
- if (null != PublicWay.activityList.get(i)) {
- PublicWay.activityList.get(i).finish();
- }
- }
- System.exit(0);
- }
- return true;
- }
- }
package com.king.photo.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import com.king.photo.R;
import com.king.photo.util.Bimp;
import com.king.photo.util.FileUtils;
import com.king.photo.util.ImageItem;
import com.king.photo.util.PublicWay;
import com.king.photo.util.Res;
//首页面activity
public class MainActivity extends Activity {
private GridView noScrollgridview;
private GridAdapter adapter;
private View parentView;
private PopupWindow pop = null;
private LinearLayout ll_popup;
public static Bitmap bimap ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Res.init(this);
bimap = BitmapFactory.decodeResource(
getResources(),
R.drawable.icon_addpic_unfocused);
PublicWay.activityList.add(this);
parentView = getLayoutInflater().inflate(R.layout.activity_selectimg, null);
setContentView(parentView);
Init();
}
public void Init() {
pop = new PopupWindow(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
pop.setWidth(LayoutParams.MATCH_PARENT);
pop.setHeight(LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);
pop.setOutsideTouchable(true);
pop.setContentView(view);
RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
Button bt1 = (Button) view
.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view
.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view
.findViewById(R.id.item_popupwindows_cancel);
parent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
photo();
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AlbumActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pop.dismiss();
ll_popup.clearAnimation();
}
});
noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
adapter = new GridAdapter(this);
adapter.update();
noScrollgridview.setAdapter(adapter);
noScrollgridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (arg2 == Bimp.tempSelectBitmap.size()) {
Log.i("ddddddd", "----------");
ll_popup.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.activity_translate_in));
pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
} else {
Intent intent = new Intent(MainActivity.this,
GalleryActivity.class);
intent.putExtra("position", "1");
intent.putExtra("ID", arg2);
startActivity(intent);
}
}
});
}
@SuppressLint("HandlerLeak")
public class GridAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int selectedPosition = -1;
private boolean shape;
public boolean isShape() {
return shape;
}
public void setShape(boolean shape) {
this.shape = shape;
}
public GridAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public void update() {
loading();
}
public int getCount() {
if(Bimp.tempSelectBitmap.size() == 9){
return 9;
}
return (Bimp.tempSelectBitmap.size() + 1);
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
public int getSelectedPosition() {
return selectedPosition;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida,
parent, false);
holder = new ViewHolder();
holder.image = (ImageView) convertView
.findViewById(R.id.item_grida_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position ==Bimp.tempSelectBitmap.size()) {
holder.image.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.icon_addpic_unfocused));
if (position == 9) {
holder.image.setVisibility(View.GONE);
}
} else {
holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
}
return convertView;
}
public class ViewHolder {
public ImageView image;
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
adapter.notifyDataSetChanged();
break;
}
super.handleMessage(msg);
}
};
public void loading() {
new Thread(new Runnable() {
public void run() {
while (true) {
if (Bimp.max == Bimp.tempSelectBitmap.size()) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
break;
} else {
Bimp.max += 1;
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}
}
}).start();
}
}
public String getString(String s) {
String path = null;
if (s == null)
return "";
for (int i = s.length() - 1; i > 0; i++) {
s.charAt(i);
}
return path;
}
protected void onRestart() {
adapter.update();
super.onRestart();
}
private static final int TAKE_PICTURE = 0x000001;
public void photo() {
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PICTURE:
if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
String fileName = String.valueOf(System.currentTimeMillis());
Bitmap bm = (Bitmap) data.getExtras().get("data");
FileUtils.saveBitmap(bm, fileName);
ImageItem takePhoto = new ImageItem();
takePhoto.setBitmap(bm);
Bimp.tempSelectBitmap.add(takePhoto);
}
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
for(int i=0;i<PublicWay.activityList.size();i++){
if (null != PublicWay.activityList.get(i)) {
PublicWay.activityList.get(i).finish();
}
}
System.exit(0);
}
return true;
}
}
下载地址 : 微信上传图片源码
备份下载地址:http://download.csdn.net/detail/jdsjlzx/8486449
补充:
此篇文章主要讲述GridView控件实现添加本地图片并显示.主要是关于GridView控件的基本操作,通常可以通过自定义继承BaseAdapter的适配器加载图片,而下面讲述的不是自定义的适配器,而是调用SimpleAdapter实现的.至于上传发布与网络交互此处不讲述,后面文章会讲!
一. 实现效果
二. 项目工程结构
三. 界面布局详细代码
1.主界面activity_main.xml
主要通过相对布局实现,第一部分是底部的TextView,中间是EditView和GridView相对布局,下面是两个按钮.同时EditView调用res/drawable-hdpi中的editview_shape.xml,GridView显示的每张图片通过griditem_addpic.xml实现.
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/container"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="com.example.suishoupaipublish.MainActivity"
- tools:ignore="MergeRootFrame" >
- <!-- 顶部添加文字 -->
- <RelativeLayout
- android:id="@+id/Layout_top"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="40dp"
- android:layout_marginTop="5dp"
- android:layout_alignParentTop="true"
- android:gravity="center">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="25sp"
- android:gravity="center"
- android:text="发布信息" />
- </RelativeLayout>
- <!-- 底部按钮 -->
- <RelativeLayout
- android:id="@+id/Layout_bottom"
- android:layout_alignParentBottom="true"
- android:layout_width="fill_parent"
- android:layout_height="50dp"
- android:gravity="center" >
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textSize="20sp"
- android:text="发布拍拍" />
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_toRightOf="@+id/button1"
- android:textSize="20sp"
- android:text="取消发布" />
- </RelativeLayout>
- <!-- 显示图片 -->
- <RelativeLayout
- android:id="@+id/Content_Layout"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_above="@id/Layout_bottom"
- android:layout_below="@id/Layout_top"
- android:gravity="center">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:layout_alignParentBottom="true" >
- <!-- 设置运行多行 设置圆角图形 黑色字体-->
- <EditText
- android:id="@+id/editText1"
- android:layout_height="120dp"
- android:layout_width="fill_parent"
- android:textColor="#000000"
- android:layout_margin="12dp"
- android:textSize="20sp"
- android:hint="随手说出你此刻的心声..."
- android:maxLength="500"
- android:singleLine="false"
- android:background="@drawable/editview_shape" />
- <!-- 网格显示图片 行列间距5dp 每列宽度90dp -->
- <GridView
- android:id="@+id/gridView1"
- android:layout_width="fill_parent"
- android:layout_height="200dp"
- android:layout_margin="10dp"
- android:background="#EFDFDF"
- android:horizontalSpacing="5dp"
- android:verticalSpacing="5dp"
- android:numColumns="4"
- android:columnWidth="90dp"
- android:stretchMode="columnWidth"
- android:gravity="center" >
- </GridView>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="(友情提示:只能添加9张图片,长按图片可以删除已添加图片)"
- android:gravity="center" />
- </LinearLayout>
- </RelativeLayout>
- </RelativeLayout>
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center"
- android:descendantFocusability="blocksDescendants"
- android:orientation="vertical" >
- <RelativeLayout
- android:layout_gravity="center"
- android:layout_width="80dp"
- android:layout_height="80dp"
- android:orientation="vertical" >
- <ImageView
- android:layout_marginTop="10dp"
- android:layout_marginRight="10dp"
- android:id="@+id/imageView1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:scaleType="fitXY"
- android:src="@drawable/gridview_addpic" />
- </RelativeLayout>
- </LinearLayout>
- <?xml version="1.0" encoding="utf-8"?>
- <shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:shape="rectangle"
- android:padding="10dp">
- <!-- 填充editView的颜色 -->
- <soild android:color="#ffffff"/>
- <!-- 设置圆角的弧度,radius半径越大,editView的边角越圆 -->
- <corners
- android:radius="15dp"
- android:bottomRightRadius="15dp"
- android:bottomLeftRadius="15dp"
- android:topLeftRadius="15dp"
- android:topRightRadius="15dp"/>
- <stroke
- android:color="#32CD32"
- android:width="4px" />
- </shape>
四. 代码详解
1.通过SimpleAdapter适配器实现实现加载图片,在gridView1.setOnItemClickListener()点击函数中响应不同操作.
2.当点击加号图片(+)时,调用本地相册通过Intent实现获取图片路径存于字符串pathImage.
3.获取图片路径后在onResume中刷新图片,通过GridView的setAdapter()和notifyDataSetChanged()()函数刷新加载图片.
4.点击图片时会获取其position,通过dialog()函数弹出对话框提示是否删除,通过remove实现删除.
具体代码如下所示:
- public class MainActivity extends Activity {
- private GridView gridView1; //网格显示缩略图
- private Button buttonPublish; //发布按钮
- private final int IMAGE_OPEN = 1; //打开图片标记
- private String pathImage; //选择图片路径
- private Bitmap bmp; //导入临时图片
- private ArrayList<HashMap<String, Object>> imageItem;
- private SimpleAdapter simpleAdapter; //适配器
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- /*
- * 防止键盘挡住输入框
- * 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
- * 希望动态调整高度 android:windowSoftInputMode="adjustResize"
- */
- getWindow().setSoftInputMode(WindowManager.LayoutParams.
- SOFT_INPUT_ADJUST_PAN);
- //锁定屏幕
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- setContentView(R.layout.activity_main);
- //获取控件对象
- gridView1 = (GridView) findViewById(R.id.gridView1);
- /*
- * 载入默认图片添加图片加号
- * 通过适配器实现
- * SimpleAdapter参数imageItem为数据源 R.layout.griditem_addpic为布局
- */
- //获取资源图片加号
- bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic);
- imageItem = new ArrayList<HashMap<String, Object>>();
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("itemImage", bmp);
- imageItem.add(map);
- simpleAdapter = new SimpleAdapter(this,
- imageItem, R.layout.griditem_addpic,
- new String[] { "itemImage"}, new int[] { R.id.imageView1});
- /*
- * HashMap载入bmp图片在GridView中不显示,但是如果载入资源ID能显示 如
- * map.put("itemImage", R.drawable.img);
- * 解决方法:
- * 1.自定义继承BaseAdapter实现
- * 2.ViewBinder()接口实现
- * 参考 http://blog.csdn.net/admin_/article/details/7257901
- */
- simpleAdapter.setViewBinder(new ViewBinder() {
- @Override
- public boolean setViewValue(View view, Object data,
- String textRepresentation) {
- // TODO Auto-generated method stub
- if(view instanceof ImageView && data instanceof Bitmap){
- ImageView i = (ImageView)view;
- i.setImageBitmap((Bitmap) data);
- return true;
- }
- return false;
- }
- });
- gridView1.setAdapter(simpleAdapter);
- /*
- * 监听GridView点击事件
- * 报错:该函数必须抽象方法 故需要手动导入import android.view.View;
- */
- gridView1.setOnItemClickListener(new OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View v, int position, long id)
- {
- if( imageItem.size() == 10) { //第一张为默认图片
- Toast.makeText(MainActivity.this, "图片数9张已满", Toast.LENGTH_SHORT).show();
- }
- else if(position == 0) { //点击图片位置为+ 0对应0张图片
- Toast.makeText(MainActivity.this, "添加图片", Toast.LENGTH_SHORT).show();
- //选择图片
- Intent intent = new Intent(Intent.ACTION_PICK,
- android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- startActivityForResult(intent, IMAGE_OPEN);
- //通过onResume()刷新数据
- }
- else {
- dialog(position);
- //Toast.makeText(MainActivity.this, "点击第"+(position + 1)+" 号图片",
- // Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- //获取图片路径 响应startActivityForResult
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- //打开图片
- if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {
- Uri uri = data.getData();
- if (!TextUtils.isEmpty(uri.getAuthority())) {
- //查询选择图片
- Cursor cursor = getContentResolver().query(
- uri,
- new String[] { MediaStore.Images.Media.DATA },
- null,
- null,
- null);
- //返回 没找到选择图片
- if (null == cursor) {
- return;
- }
- //光标移动至开头 获取图片路径
- cursor.moveToFirst();
- pathImage = cursor.getString(cursor
- .getColumnIndex(MediaStore.Images.Media.DATA));
- }
- } //end if 打开图片
- }
- //刷新图片
- @Override
- protected void onResume() {
- super.onResume();
- if(!TextUtils.isEmpty(pathImage)){
- Bitmap addbmp=BitmapFactory.decodeFile(pathImage);
- HashMap<String, Object> map = new HashMap<String, Object>();
- map.put("itemImage", addbmp);
- imageItem.add(map);
- simpleAdapter = new SimpleAdapter(this,
- imageItem, R.layout.griditem_addpic,
- new String[] { "itemImage"}, new int[] { R.id.imageView1});
- simpleAdapter.setViewBinder(new ViewBinder() {
- @Override
- public boolean setViewValue(View view, Object data,
- String textRepresentation) {
- // TODO Auto-generated method stub
- if(view instanceof ImageView && data instanceof Bitmap){
- ImageView i = (ImageView)view;
- i.setImageBitmap((Bitmap) data);
- return true;
- }
- return false;
- }
- });
- gridView1.setAdapter(simpleAdapter);
- simpleAdapter.notifyDataSetChanged();
- //刷新后释放防止手机休眠后自动添加
- pathImage = null;
- }
- }
- /*
- * Dialog对话框提示用户删除操作
- * position为删除图片位置
- */
- protected void dialog(final int position) {
- AlertDialog.Builder builder = new Builder(MainActivity.this);
- builder.setMessage("确认移除已添加图片吗?");
- builder.setTitle("提示");
- builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- imageItem.remove(position);
- simpleAdapter.notifyDataSetChanged();
- }
- });
- builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.create().show();
- }
- }
- <!-- 申明网络权限 -->
- <uses-permission android:name="android.permission.INTERNET" />
- <!-- 申明权限 操作SD卡 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
五. 总结
这时有两种解决方法,一种是自定义继承BaseAdapter的适配器实现;另一种方法则是如上所示通过ViewBinder()接口实现,感谢博主dmin_提供的方法.
下载地址:http://download.csdn.net/detail/eastmount/8237429
下面再分享个图片处理的博客。
demo下载地址:
http://download.csdn.net/detail/eastmount/8432127
http://pan.baidu.com/s/1c0kz3by
一. 项目结构及界面
项目工程结构如下图所示:
同时Layout中有五个xml子布局,采用PopupWindow形式显示五个不同的处理,同时该demo比较好移植,将文件依次复制过去并且MainActivity改成子活动,即可调用.
其中部分界面如下:
二. 图像查看功能
点击主界面GridView中"+"添加图片后,可以选择从相册添加或照相,加载图片进行到处理界面后,点击底部"查看"按钮它会有选中的效果(图标颜色变蓝&背景颜色加深).同时PopupWindow弹出如下界面:
[Android] 使用Matrix矩阵类对图像进行缩放、旋转、对比度、亮度处理
[Android] 触屏setOnTouchListener实现图片缩放、移动、绘制和添加水印
其他效果如下,同时存在几个问题:
1.图像绘图保存我没有做
2.移动和缩放图像,上传的都是原图大小
3.添加水印功能感觉简单就没实现
三. 图像增强功能
图像增强主要是通过3个进度条SeekBar实现,可以调节图像的饱和度、亮度和色相.当饱和度等于0时就是黑白二值图像,三个滑动条可以相互调节.如下图所示:
[Android] 使用Matrix矩阵类对图像进行缩放、旋转、对比度、亮度处理
[Android] 图像处理整合之处理ColorMatrix和Intend传递路径显示图像
[Android] 底部菜单布局+PopupWindows实现弹出菜单功能(初级篇)
同时需要注意一个问题: 设置滑动条时需要设置其区间,同时在弹出PopupWindow注意其宽度和不同手机的适屏处理.
该部分算法处理代码如下,每部分算法调用后返回值都是bitmap,然后调用imageShow.setImageBitmap(mbmp);直接显示.
四. 图像特效功能
PopupWindow弹出如下界面,主要包括:怀旧、浮雕、光照、素描和锐化处理.
[Android] 通过Menu实现图片怀旧、浮雕、模糊、光照和素描效果
[Android] 图像各种处理系列文章合集 (草稿 强推)
同时算法中存在一些问题,一个就是效率不高,有好友建议C写算法来调用,但是该文章仅是课堂作业,提供一种方法供大家参考.同时在图像素描算法效果不好,锐化处理应该也不对(可参考博客),光照效果是从中心向边沿映射,用户可自己设置光照直径和方向.
五. 图像相框添加
最后是图像相框合成,如下图所示.我采用的是照相后合成图片:
[Android] 给图像添加相框、圆形圆角显示图片、图像合成知识
六. 总结及感想
该处理过程中的底部五个按钮切换背景和颜色详见代码ProcessActivity.java,主要是通切换两张图片和背景实现.如果每个界面显示不同内容,建议使用Fragment滑动实现.参考:
[Android] 使用Include布局+Fragment滑动切换屏幕
[Android] 通过GridView仿微信动态添加本地图片
随手拍我还是比较满意的,其中后台数据库我们使用的是新浪SAE做的,同时ListView刷新拍拍也非常不错!效果如下:
但是由于整个项目是大家一起完成,包括网络、数据库(SAE)、ListView(引用开源),所以只能共享我做的那部分.抱歉~如果有时间可以写些关于Android网络方面的文章,包括如何上传图片(URL链接存储在云盘中)、获取数据库内容等操作.
PS:最近其实挺烦躁的,一方面这学期确实忙成狗了,寒假也还有个作业.但在火车上我还是挺平静的——听着调皮的钢琴曲,看着窗外流逝的繁华,不知道从什么时候自己已经喜欢上了这种26小时独处的感觉.感受颇多啊!另一个挺令我心烦的就是回家后不久就去做了个手指的小手术,今天写完这篇文章,心情稍微好点!蓦然回首,突然发现这辈子我最对不住的人居然是我自己,希望来年对自己有点,尤其是对自己的身体.同时有机会,找份实习吧!但幸运的是,每每分享一些博客、完成一些项目后都能给我带来一份快乐.
希望文章对大家有所帮助~
最后用最近看的《老人与海》结束这篇文章:
生活总是让我们遍体鳞伤,但到后来,那些受伤的地方一定会变成我们最强壮的地方.
(By:Eastmount 2015-2-7 夜11点 http://blog.csdn.net/eastmount/)