当前位置: 移动技术网 > IT编程>移动开发>Android > [Android] 通过GridView仿微信动态添加本地图片示例代码

[Android] 通过GridView仿微信动态添加本地图片示例代码

2019年07月24日  | 移动技术网IT编程  | 我要评论

seokoog,古镇,大良实验小学网站

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

一. 实现效果

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

    

二. 项目工程结构

三. 界面布局详细代码

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> 

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

<?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> 

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

<?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()接口实现 
     */ 
    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(); 
  } 
 
} 

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

<!-- 申明网络权限 --> 
<uses-permission android:name="android.permission.internet" /> 
<!-- 申明权限 操作sd卡 -->  
<uses-permission android:name="android.permission.write_external_storage" /> 

五. 总结

该文章需要注意一个地方:在使用simpleadapter适配器加载bmp图片时,可能在gridview中不显示.即hashmap中map.put("itemimage",bmp)不显示图片,而使用put装入r.drawable.img却能显示.

这时有两种解决方法,一种是自定义继承baseadapter的适配器实现;另一种方法则是如上所示通过viewbinder()接口实现,感谢博主dmin_提供的方法.

demo下载地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网