Android中使用GridView实现仿微信图片上传功能(附源代码)
程序员文章站
2023-12-15 09:48:58
由于工作要求最近在使用gridview完成图片的批量上传功能,我的例子当中包含仿微信图片上传、拍照、本地选择、相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能...
由于工作要求最近在使用gridview完成图片的批量上传功能,我的例子当中包含仿微信图片上传、拍照、本地选择、相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能对您有所帮助。
直接上图,下面的图片就是点击“加号”后弹出的对话框,通过对话框可以根据自己需求进行相片选择。
项目结构:
下面直接上代码。
整体的布局文件activity_main.xml
<linearlayout 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:background="@drawable/index" android:orientation="vertical" > <linearlayout android:layout_width="match_parent" android:layout_height="44dp" android:background="#24cf5f" android:orientation="horizontal" > <imageview android:id="@+id/back" android:layout_width="match_parent" android:layout_height="20dp" android:layout_gravity="center" android:layout_weight="5" android:src="@drawable/back" /> <textview android:layout_width="fill_parent" android:layout_height="44dp" android:layout_weight="1" android:gravity="center" android:paddingright="40dp" android:text="图片上传" android:textcolor="#ffffff" android:textsize="30px" /> </linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <scrollview android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" > <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <linearlayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <linearlayout android:layout_width="match_parent" android:layout_height="60dp" android:layout_weight="1" android:orientation="vertical" > <textview android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="请选择上传的图片" /> <textview android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="(友情提示:图片最多可添加9张,点击可删除选择的图片)" android:textsize="18px" /> </linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" > <com.yihang.mygridview.mygridview android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="111" android:columnwidth="90dp" android:gravity="center" android:horizontalspacing="5dp" android:numcolumns="4" android:stretchmode="columnwidth" android:verticalspacing="5dp" /> </linearlayout> </linearlayout> </scrollview> <button android:id="@+id/bt_submit" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="bottom" android:layout_weight="5.2" android:background="#24cf5f" android:text="上传" android:textcolor="#ffffff" android:textsize="16sp" /> </linearlayout>
activity:mainactivity
package com.yihang.activity; import java.io.bytearrayoutputstream; import java.io.file; import java.util.arraylist; import java.util.hashmap; import android.app.activity; import android.app.alertdialog; import android.app.alertdialog.builder; import android.content.dialoginterface; import android.content.intent; import android.content.pm.activityinfo; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.net.uri; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.text.textutils; import android.view.layoutinflater; import android.view.view; import android.view.window; import android.view.windowmanager; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.gridview; import android.widget.imageview; import android.widget.simpleadapter; import android.widget.simpleadapter.viewbinder; import android.widget.toast; import com.yihang.dialog.mydialog; import com.yihang.dialog.mydialog.onbuttonclicklistener; import com.yihang.photodemo.r; public class mainactivity extends activity implements onbuttonclicklistener, onitemclicklistener{ private mydialog dialog;// 图片选择对话框 public static final int none = 0; public static final int photohraph = 1;// 拍照 public static final int photozoom = 2; // 缩放 public static final int photoresoult = 3;// 结果 public static final string image_unspecified = "image/*"; private gridview gridview; // 网格显示缩略图 private final int image_open = 4; // 打开图片标记 private string pathimage; // 选择图片路径 private bitmap bmp; // 导入临时图片 private arraylist<hashmap<string, object>> imageitem; private simpleadapter simpleadapter; // 适配器 @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); requestwindowfeature(window.feature_no_title); /* * 防止键盘挡住输入框 不希望遮挡设置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); init(); initdata(); } private void init() { gridview = (gridview) findviewbyid(r.id.gridview); gridview.setonitemclicklistener(this); dialog = new mydialog(this); dialog.setonbuttonclicklistener(this); // activity中调用其他activity中组件的方法 layoutinflater layout = this.getlayoutinflater(); view view = layout.inflate(r.layout.layout_select_photo, null); } private void initdata() { /* * 载入默认图片添加图片加号 */ 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 }); 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; } }); gridview.setadapter(simpleadapter); } @override public void camera() { // todo auto-generated method stub intent intent = new intent(mediastore.action_image_capture); intent.putextra(mediastore.extra_output, uri.fromfile(new file( environment.getexternalstoragedirectory(), "temp.jpg"))); startactivityforresult(intent, photohraph); } @override public void gallery() { // todo auto-generated method stub intent intent = new intent(intent.action_pick, android.provider.mediastore.images.media.external_content_uri); startactivityforresult(intent, image_open); } @override public void cancel() { // todo auto-generated method stub dialog.cancel(); } @override protected void onactivityresult(int requestcode, int resultcode, intent data) { // todo auto-generated method stub super.onactivityresult(requestcode, resultcode, data); if (resultcode == none) return; // 拍照 if (requestcode == photohraph) { // 设置文件保存路径这里放在跟目录下 file picture = new file(environment.getexternalstoragedirectory() + "/temp.jpg"); startphotozoom(uri.fromfile(picture)); } if (data == null) return; // 处理结果 if (requestcode == photoresoult) { bundle extras = data.getextras(); if (extras != null) { bitmap photo = extras.getparcelable("data"); bytearrayoutputstream stream = new bytearrayoutputstream(); photo.compress(bitmap.compressformat.jpeg, 75, stream);// (0-100)压缩文件 // 将图片放入gridview中 hashmap<string, object> map = new hashmap<string, object>(); map.put("itemimage", photo); 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; } }); gridview.setadapter(simpleadapter); simpleadapter.notifydatasetchanged(); dialog.dismiss(); } } // 打开图片 if (resultcode == result_ok && requestcode == image_open) { startphotozoom(data.getdata()); } super.onactivityresult(requestcode, resultcode, data); } @override protected void onresume() { // todo auto-generated method stub 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; } }); gridview.setadapter(simpleadapter); simpleadapter.notifydatasetchanged(); // 刷新后释放防止手机休眠后自动添加 pathimage = null; dialog.dismiss(); } } @override public void onitemclick(adapterview<?> parent, view v, int position, long id) { // todo auto-generated method stub if (imageitem.size() == 10) { // 第一张为默认图片 toast.maketext(mainactivity.this, "图片数9张已满", toast.length_short).show(); } else if (position == 0) { // 点击图片位置为+ 0对应0张图片 // 选择图片 dialog.show(); // 通过onresume()刷新数据 } else { dialog(position); } } /* * 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(); } public void startphotozoom(uri uri) { intent intent = new intent("com.android.camera.action.crop"); intent.setdataandtype(uri, image_unspecified); intent.putextra("crop", "true"); // aspectx aspecty 是宽高的比例 intent.putextra("aspectx", 1); intent.putextra("aspecty", 1); // outputx outputy 是裁剪图片宽高 intent.putextra("outputx", 64); intent.putextra("outputy", 64); intent.putextra("return-data", true); startactivityforresult(intent, photoresoult); } }
弹出的对话框(仿照微信来完成):mydialog
package com.yihang.dialog; import com.yihang.photodemo.r; import android.app.dialog; import android.content.context; import android.view.gravity; import android.view.view; import android.view.viewgroup; import android.view.window; import android.view.view.onclicklistener; /** * 对话框实现类 * @author admin * */ public class mydialog extends dialog implements onclicklistener { public mydialog(context context) { super(context,r.style.mydialog); //初始化布局 setcontentview(r.layout.layout_select_photo); window dialogwindow = getwindow(); dialogwindow.setlayout(viewgroup.layoutparams.fill_parent, viewgroup.layoutparams.wrap_content); dialogwindow.setgravity(gravity.bottom); setcanceledontouchoutside(true); findviewbyid(r.id.btn_camera).setonclicklistener(this); findviewbyid(r.id.btn_gallery).setonclicklistener(this); findviewbyid(r.id.btn_cancel).setonclicklistener(this); } @override public void onclick(view v) { // todo auto-generated method stub switch (v.getid()) { case r.id.btn_camera: onbuttonclicklistener.camera(); break; case r.id.btn_gallery: onbuttonclicklistener.gallery(); break; case r.id.btn_cancel: onbuttonclicklistener.cancel(); break; default: break; } } /** * 按钮的监听器 * @author orathee * @date 2014年3月20日 下午4:28:39 */ public interface onbuttonclicklistener{ void camera(); void gallery(); void cancel(); } private onbuttonclicklistener onbuttonclicklistener; public onbuttonclicklistener getonbuttonclicklistener() { return onbuttonclicklistener; } public void setonbuttonclicklistener(onbuttonclicklistener onbuttonclicklistener) { this.onbuttonclicklistener = onbuttonclicklistener; } }
对话框的布局文件:layout_select_photo.xml
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom"> <linearlayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="@drawable/btn_style_alert_dialog_background" android:padding="20dp"> <textview android:id="@+id/btn_camera" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textsize="18sp" android:background="@drawable/btn_style_alert_dialog_button" android:textcolor="#0f0f0f" android:text="拍照" android:shadowdx="0.5" android:shadowdy="0.5" android:shadowradius="0.5" android:shadowcolor="#ffffff" android:layout_marginbottom="10dp" android:padding="10dp" android:gravity="center"/> <textview android:id="@+id/btn_gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textsize="18sp" android:background="@drawable/btn_style_alert_dialog_button" android:textcolor="#0f0f0f" android:text="从相册中选择" android:shadowdx="0.5" android:shadowdy="0.5" android:shadowradius="0.5" android:shadowcolor="#ffffff" android:layout_marginbottom="10dp" android:padding="10dp" android:gravity="center"/> <textview android:id="@+id/btn_cancel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/btn_style_alert_dialog_cancel" android:textcolor="#ffffff" android:textsize="18sp" android:text="取消" android:shadowdx="0.5" android:shadowdy="0.5" android:shadowradius="0.5" android:shadowcolor="#000000" android:layout_margintop="10dp" android:padding="10dp" android:gravity="center"/> </linearlayout> </linearlayout>
自定义的gridview:
package com.yihang.mygridview; import android.content.context; import android.util.attributeset; import android.widget.gridview; public class mygridview extends gridview { public mygridview(context context, attributeset attrs) { super(context, attrs); // todo auto-generated constructor stub } public mygridview(context context) { super(context); } public mygridview(context context, attributeset attrs, int defstyle) { super(context); } @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { // todo auto-generated method stub int expandspec = measurespec.makemeasurespec(integer.max_value >> 2, measurespec.at_most); super.onmeasure(widthmeasurespec, expandspec); } }
源码下载:http://xiazai.jb51.net/201707/yuanma/photodemo.rar
总结
以上所述是小编给大家介绍的android中使用gridview实现仿微信图片上传功能(附源代码),希望对大家有所帮助