原文:http://blog.csdn.net/eastmount/article/details/41808179

前面文章讲述的都是"随手拍"中图像处理的操作,此篇文章主要讲述GridView控件实现添加本地图片并显示.主要是关于GridView控件的基本操作,通常可以通过自定义继承BaseAdapter的适配器加载图片,而下面讲述的不是自定义的适配器,而是调用SimpleAdapter实现的.至于上传发布与网络交互此处不讲述,后面文章会讲!

一. 实现效果

    主要是通过点击+从本地相册中添加图片,同时显示图片至GridView.点击图片可以进行删除操作,同时界面中的发布EditView控件也很好看,不足之处在于+好没有移动至最后,但原理相同.
   

二. 项目工程结构

 

 

三. 界面布局详细代码

    1.主界面activity_main.xml
    主要通过相对布局实现,第一部分是底部的TextView,中间是EditView和GridView相对布局,下面是两个按钮.同时EditView调用res/drawable-hdpi中的editview_shape.xml,GridView显示的每张图片通过griditem_addpic.xml实现.

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:id="@+id/container"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. tools:context="com.example.suishoupaipublish.MainActivity"
  7. tools:ignore="MergeRootFrame" >
  8. <!-- 顶部添加文字 -->
  9. <RelativeLayout
  10. android:id="@+id/Layout_top"
  11. android:orientation="horizontal"
  12. android:layout_width="fill_parent"
  13. android:layout_height="40dp"
  14. android:layout_marginTop="5dp"
  15. android:layout_alignParentTop="true"
  16. android:gravity="center">
  17. <TextView
  18. android:layout_width="fill_parent"
  19. android:layout_height="wrap_content"
  20. android:textSize="25sp"
  21. android:gravity="center"
  22. android:text="发布信息" />
  23. </RelativeLayout>
  24. <!-- 底部按钮 -->
  25. <RelativeLayout
  26. android:id="@+id/Layout_bottom"
  27. android:layout_alignParentBottom="true"
  28. android:layout_width="fill_parent"
  29. android:layout_height="50dp"
  30. android:gravity="center" >
  31. <Button
  32. android:id="@+id/button1"
  33. android:layout_width="wrap_content"
  34. android:layout_height="fill_parent"
  35. android:textSize="20sp"
  36. android:text="发布拍拍" />
  37. <Button
  38. android:id="@+id/button2"
  39. android:layout_width="wrap_content"
  40. android:layout_height="fill_parent"
  41. android:layout_toRightOf="@+id/button1"
  42. android:textSize="20sp"
  43. android:text="取消发布" />
  44. </RelativeLayout>
  45. <!-- 显示图片 -->
  46. <RelativeLayout
  47. android:id="@+id/Content_Layout"
  48. android:layout_width="fill_parent"
  49. android:layout_height="fill_parent"
  50. android:layout_above="@id/Layout_bottom"
  51. android:layout_below="@id/Layout_top"
  52. android:gravity="center">
  53. <LinearLayout
  54. android:layout_width="match_parent"
  55. android:layout_height="match_parent"
  56. android:orientation="vertical"
  57. android:layout_alignParentBottom="true" >
  58. <!-- 设置运行多行 设置圆角图形 黑色字体-->
  59. <EditText
  60. android:id="@+id/editText1"
  61. android:layout_height="120dp"
  62. android:layout_width="fill_parent"
  63. android:textColor="#000000"
  64. android:layout_margin="12dp"
  65. android:textSize="20sp"
  66. android:hint="随手说出你此刻的心声..."
  67. android:maxLength="500"
  68. android:singleLine="false"
  69. android:background="@drawable/editview_shape" />
  70. <!-- 网格显示图片 行列间距5dp 每列宽度90dp -->
  71. <GridView
  72. android:id="@+id/gridView1"
  73. android:layout_width="fill_parent"
  74. android:layout_height="200dp"
  75. android:layout_margin="10dp"
  76. android:background="#EFDFDF"
  77. android:horizontalSpacing="5dp"
  78. android:verticalSpacing="5dp"
  79. android:numColumns="4"
  80. android:columnWidth="90dp"
  81. android:stretchMode="columnWidth"
  82. android:gravity="center" >
  83. </GridView>
  84. <TextView
  85. android:layout_width="fill_parent"
  86. android:layout_height="wrap_content"
  87. android:text="(友情提示:只能添加9张图片,长按图片可以删除已添加图片)"
  88. android:gravity="center" />
  89. </LinearLayout>
  90. </RelativeLayout>
  91. </RelativeLayout>

    2.显示ImageView图片布局griditem_addpic.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:gravity="center"
  6. android:descendantFocusability="blocksDescendants"
  7. android:orientation="vertical" >
  8. <RelativeLayout
  9. android:layout_gravity="center"
  10. android:layout_width="80dp"
  11. android:layout_height="80dp"
  12. android:orientation="vertical" >
  13. <ImageView
  14. android:layout_marginTop="10dp"
  15. android:layout_marginRight="10dp"
  16. android:id="@+id/imageView1"
  17. android:layout_width="fill_parent"
  18. android:layout_height="fill_parent"
  19. android:scaleType="fitXY"
  20. android:src="@drawable/gridview_addpic" />
  21. </RelativeLayout>
  22. </LinearLayout>

    3.设置EditView控件圆角和颜色 editview_shape.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle"
  4. android:padding="10dp">
  5. <!-- 填充editView的颜色 -->
  6. <soild android:color="#ffffff"/>
  7. <!-- 设置圆角的弧度,radius半径越大,editView的边角越圆 -->
  8. <corners
  9. android:radius="15dp"
  10. android:bottomRightRadius="15dp"
  11. android:bottomLeftRadius="15dp"
  12. android:topLeftRadius="15dp"
  13. android:topRightRadius="15dp"/>
  14. <stroke
  15. android:color="#32CD32"
  16. android:width="4px" />
  17. </shape>

四. 代码详解

 
    它主要是思想如下:
    1.通过SimpleAdapter适配器实现实现加载图片,在gridView1.setOnItemClickListener()点击函数中响应不同操作.
    2.当点击加号图片(+)时,调用本地相册通过Intent实现获取图片路径存于字符串pathImage.
    3.获取图片路径后在onResume中刷新图片,通过GridView的setAdapter()和notifyDataSetChanged()()函数刷新加载图片.
    4.点击图片时会获取其position,通过dialog()函数弹出对话框提示是否删除,通过remove实现删除.
    具体代码如下所示:
  1. public class MainActivity extends Activity {
  2. private GridView gridView1;              //网格显示缩略图
  3. private Button buttonPublish;            //发布按钮
  4. private final int IMAGE_OPEN = 1;        //打开图片标记
  5. private String pathImage;                //选择图片路径
  6. private Bitmap bmp;                      //导入临时图片
  7. private ArrayList<HashMap<String, Object>> imageItem;
  8. private SimpleAdapter simpleAdapter;     //适配器
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. /*
  14. * 防止键盘挡住输入框
  15. * 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
  16. * 希望动态调整高度 android:windowSoftInputMode="adjustResize"
  17. */
  18. getWindow().setSoftInputMode(WindowManager.LayoutParams.
  19. SOFT_INPUT_ADJUST_PAN);
  20. //锁定屏幕
  21. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  22. setContentView(R.layout.activity_main);
  23. //获取控件对象
  24. gridView1 = (GridView) findViewById(R.id.gridView1);
  25. /*
  26. * 载入默认图片添加图片加号
  27. * 通过适配器实现
  28. * SimpleAdapter参数imageItem为数据源 R.layout.griditem_addpic为布局
  29. */
  30. //获取资源图片加号
  31. bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic);
  32. imageItem = new ArrayList<HashMap<String, Object>>();
  33. HashMap<String, Object> map = new HashMap<String, Object>();
  34. map.put("itemImage", bmp);
  35. imageItem.add(map);
  36. simpleAdapter = new SimpleAdapter(this,
  37. imageItem, R.layout.griditem_addpic,
  38. new String[] { "itemImage"}, new int[] { R.id.imageView1});
  39. /*
  40. * HashMap载入bmp图片在GridView中不显示,但是如果载入资源ID能显示 如
  41. * map.put("itemImage", R.drawable.img);
  42. * 解决方法:
  43. *              1.自定义继承BaseAdapter实现
  44. *              2.ViewBinder()接口实现
  45. *  参考 http://blog.csdn.net/admin_/article/details/7257901
  46. */
  47. simpleAdapter.setViewBinder(new ViewBinder() {
  48. @Override
  49. public boolean setViewValue(View view, Object data,
  50. String textRepresentation) {
  51. // TODO Auto-generated method stub
  52. if(view instanceof ImageView && data instanceof Bitmap){
  53. ImageView i = (ImageView)view;
  54. i.setImageBitmap((Bitmap) data);
  55. return true;
  56. }
  57. return false;
  58. }
  59. });
  60. gridView1.setAdapter(simpleAdapter);
  61. /*
  62. * 监听GridView点击事件
  63. * 报错:该函数必须抽象方法 故需要手动导入import android.view.View;
  64. */
  65. gridView1.setOnItemClickListener(new OnItemClickListener() {
  66. @Override
  67. public void onItemClick(AdapterView<?> parent, View v, int position, long id)
  68. {
  69. if( imageItem.size() == 10) { //第一张为默认图片
  70. Toast.makeText(MainActivity.this, "图片数9张已满", Toast.LENGTH_SHORT).show();
  71. }
  72. else if(position == 0) { //点击图片位置为+ 0对应0张图片
  73. Toast.makeText(MainActivity.this, "添加图片", Toast.LENGTH_SHORT).show();
  74. //选择图片
  75. Intent intent = new Intent(Intent.ACTION_PICK,
  76. android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  77. startActivityForResult(intent, IMAGE_OPEN);
  78. //通过onResume()刷新数据
  79. }
  80. else {
  81. dialog(position);
  82. //Toast.makeText(MainActivity.this, "点击第"+(position + 1)+" 号图片",
  83. //      Toast.LENGTH_SHORT).show();
  84. }
  85. }
  86. });
  87. }
  88. //获取图片路径 响应startActivityForResult
  89. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  90. super.onActivityResult(requestCode, resultCode, data);
  91. //打开图片
  92. if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {
  93. Uri uri = data.getData();
  94. if (!TextUtils.isEmpty(uri.getAuthority())) {
  95. //查询选择图片
  96. Cursor cursor = getContentResolver().query(
  97. uri,
  98. new String[] { MediaStore.Images.Media.DATA },
  99. null,
  100. null,
  101. null);
  102. //返回 没找到选择图片
  103. if (null == cursor) {
  104. return;
  105. }
  106. //光标移动至开头 获取图片路径
  107. cursor.moveToFirst();
  108. pathImage = cursor.getString(cursor
  109. .getColumnIndex(MediaStore.Images.Media.DATA));
  110. }
  111. }  //end if 打开图片
  112. }
  113. //刷新图片
  114. @Override
  115. protected void onResume() {
  116. super.onResume();
  117. if(!TextUtils.isEmpty(pathImage)){
  118. Bitmap addbmp=BitmapFactory.decodeFile(pathImage);
  119. HashMap<String, Object> map = new HashMap<String, Object>();
  120. map.put("itemImage", addbmp);
  121. imageItem.add(map);
  122. simpleAdapter = new SimpleAdapter(this,
  123. imageItem, R.layout.griditem_addpic,
  124. new String[] { "itemImage"}, new int[] { R.id.imageView1});
  125. simpleAdapter.setViewBinder(new ViewBinder() {
  126. @Override
  127. public boolean setViewValue(View view, Object data,
  128. String textRepresentation) {
  129. // TODO Auto-generated method stub
  130. if(view instanceof ImageView && data instanceof Bitmap){
  131. ImageView i = (ImageView)view;
  132. i.setImageBitmap((Bitmap) data);
  133. return true;
  134. }
  135. return false;
  136. }
  137. });
  138. gridView1.setAdapter(simpleAdapter);
  139. simpleAdapter.notifyDataSetChanged();
  140. //刷新后释放防止手机休眠后自动添加
  141. pathImage = null;
  142. }
  143. }
  144. /*
  145. * Dialog对话框提示用户删除操作
  146. * position为删除图片位置
  147. */
  148. protected void dialog(final int position) {
  149. AlertDialog.Builder builder = new Builder(MainActivity.this);
  150. builder.setMessage("确认移除已添加图片吗?");
  151. builder.setTitle("提示");
  152. builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
  153. @Override
  154. public void onClick(DialogInterface dialog, int which) {
  155. dialog.dismiss();
  156. imageItem.remove(position);
  157. simpleAdapter.notifyDataSetChanged();
  158. }
  159. });
  160. builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
  161. @Override
  162. public void onClick(DialogInterface dialog, int which) {
  163. dialog.dismiss();
  164. }
  165. });
  166. builder.create().show();
  167. }
  168. }

    同时需要在AndroidMainfest.xml中添加权限操作SD卡和网络上传至服务器.

  1. <!-- 申明网络权限  -->
  2. <uses-permission android:name="android.permission.INTERNET" />
  3. <!-- 申明权限 操作SD卡 -->
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

五. 总结

    
    该文章需要注意一个地方:在使用SimpleAdapter适配器加载bmp图片时,可能在GridView中不显示.即HashMap中map.put("itemImage",bmp)不显示图片,而使用put装入R.drawable.img却能显示.
    这时有两种解决方法,一种是自定义继承BaseAdapter的适配器实现;另一种方法则是如上所示通过ViewBinder()接口实现,感谢博主dmin_提供的方法.
    下载地址:http://download.csdn.net/detail/eastmount/8237429
    最后希望文章对大家有所帮助,如果有错误或不足之处,请海涵~最近学校网比较差,回复别人都不行.
    (By:Eastmount 2014-12-8 晚9点 http://blog.csdn.net/eastmount/)

[Android] 通过GridView仿微信动态添加本地图片的更多相关文章

  1. Android 使用GridView+仿微信图片上传功能(附源代码)

    由于工作要求最近在使用GridView完成图片的批量上传功能,我的例子当中包含仿微信图片上传.拍照.本地选择.相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能对您有所帮助. 直接上图,下 ...

  2. [Android] Android 手机下 仿 微信 客户端 界面 -- 微聊

    Android 手机下 仿 微信 客户端 界面 -- 微聊 (包括聊天列表 + 聊天对话页 + 朋友圈列表页 + 我的/发现 列表页) 项目演示: 功能说明: 1)底部标签切换 (TabHost + ...

  3. android之使用GridView+仿微信图片上传功能

    由于工作要求最近在使用GridView完成图片的批量上传功能,我的例子当中包含仿微信图片上传.拍照.本地选择.相片裁剪等功能,如果有需要的朋友可以看一下,希望我的实际经验能对您有所帮助. 直接上图,下 ...

  4. Android开发之使用GridView+仿微信图片上传功能(附源代码)

    前言:如果转载文章请声明转载自:https://i.cnblogs.com/EditPosts.aspx?postid=7419021  .另外针对有些网站转载本人的文章结果源码链接不对的问题,本人在 ...

  5. Android Studio精彩案例(二)《仿微信动态点击底部tab切换Fragment》

    转载本专栏文章,请注明出处,尊重原创 .文章博客地址:道龙的博客 现在很多的App要么顶部带有tab,要么就底部带有tab.用户通过点击tab从而切换不同的页面(大部分情况时去切换fragment). ...

  6. android 在 ListView 的 item 中插入 GridView 仿微信朋友圈图片显示。

    转载请声明出处(http://www.cnblogs.com/linguanh/) 先上张效果图: 1,思路简述 这个肯定是要重写 baseAdapter的了,这里我分了两个数据适配器,一个是自定义的 ...

  7. iOS/Android 浏览器(h5)及微信中唤起本地APP

    在移动互联网,链接是比较重要的传播媒质,但很多时候我们又希望用户能够回到APP中,这就要求APP可以通过浏览器或在微信中被方便地唤起. 这是一个既直观又很好的用户体验,但在实现过程中会遇到各种问题: ...

  8. android 随手记 仿微信的popwindow

    /把文字控件添加监听,点击弹出自定义窗口 tv.setOnClickListener(new OnClickListener() { public void onClick(View v) { //实 ...

  9. Android 仿微信朋友圈发表图片拖拽和删除功能

    朋友圈实现原理 我们使用 Android Device Monitor 来分析朋友圈发布图片的界面实现原理.如果需要分析其他应用的界面实现也是采用这种方法哦. 打开 Android Device Mo ...

随机推荐

  1. elasticsearch 2.4.0安装说明

    首先从官网下载安装包,是个压缩文件,然后解压 在es目录下找到es的配置文件 修改集群(cluster)名称 PS:一般情况下一台机只部署一个es程序,也就是一个集群,默认集群名是ewater_mai ...

  2. 微信小程序组件解读和分析:一、view(视图容器 )

    view组件说明:    视图容器    跟HTML代码中的DIV一样,可以包裹其他的组件,也可以被包裹在其他的组件内部.用起来比较自由随意,没有固定的结构. view组件的用法: 示例项目的wxml ...

  3. php中session实现机制

    一.默认机制,用磁盘文件来实现PHP会话.php.ini配置:session.save_handler = files 1.session_start() A. session_start()是ses ...

  4. [Java 8] (9) Lambda表达式对递归的优化(下) - 使用备忘录模式(Memoization Pattern) .

    使用备忘录模式(Memoization Pattern)提高性能 这个模式说白了,就是将需要进行大量计算的结果缓存起来,然后在下次需要的时候直接取得就好了.因此,底层只需要使用一个Map就够了. 但是 ...

  5. Codeforces GYM 100741A . Queries

    time limit per test 0.25 seconds memory limit per test 64 megabytes input standard input output stan ...

  6. [Github筆記] 清除所有 Commit 紀錄

    # 把原來的 git 移除掉 sudo rm .git -r # 初始化 git init git remote add origin https://github.com/username/repo ...

  7. 推荐一个高大上的网易云音乐命令行播放工具:musicbox

    网易云音乐上有很多适合程序猿的歌单,但是今天文章介绍的不是这些适合程序员工作时听的歌,而是一个用Python开发的开源播放器,专门适用于网易云音乐的播放.这个播放器的名称为MusicBox, 特色是用 ...

  8. VC++绘制金刚石(MFC)

    void CTxx1View::OnDraw(CDC* pDC){ CTxx1Doc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // TODO: add d ...

  9. 嵌入式C语言-学习书籍推荐(pdf附上百度云链接)

    先推荐学习视频网站: https://www.bilibili.com/video/av22631677?from=search&seid=800092160484173881 书籍只推荐2本 ...

  10. Promise 理解与使用

    个人觉得这篇博客写的非常详细且易懂,推荐给小伙伴们~ https://www.cnblogs.com/lvdabao/p/es6-promise-1.html#!comments