当前位置: 萬仟网 > 移动技术>移动开发>Android > Android 多图上传后将图片进行九宫格展示的实例代码

Android 多图上传后将图片进行九宫格展示的实例代码

2020年11月20日  | 萬仟网移动技术  | 我要评论
不多说上代码public abstract class ninegridadapter { protected context context; protected list list; pub

不多说上代码

public abstract class ninegridadapter {
  protected context context;
  protected list list;

  public ninegridadapter(context context, list list) {
    this.context = context;
    this.list = list;
  }

  public abstract int getcount();

  public abstract string geturl(int positopn);

  public abstract object getitem(int position);

  public abstract long getitemid(int position);

  public abstract view getview(int i, view view);

}
package com.wd.weidologin.pic;

import android.content.context;
import android.util.attributeset;
import android.util.displaymetrics;
import android.view.view;
import android.view.viewgroup;
import android.widget.imageview;

public class ninegridlayout extends viewgroup {
  private ninegridadapter adapter;
  private onitemclicklisterner onitemclicklisterner;

  // 行间距
  private int linespace;
  //列间距
  private int gap;

  private final int default_width = 140;

  private int columns;//
  private int rows;//
  private int totalwidth;
  private context context;
  int singlewidth = 0, singleheight = 0;
  private int defaultwidth, defaultheight;

  private int oldcount;

  public ninegridlayout(context context) {
    this(context, null);
  }

  public ninegridlayout(context context, attributeset attrs) {
    this(context, attrs, 0);
  }

  public ninegridlayout(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
    this.context = context;
    gap = dip2px(context, 10);
    linespace = dip2px(context,10);
    viewgroup.layoutparams lp = new viewgroup.layoutparams(viewgroup.layoutparams.wrap_content,
        viewgroup.layoutparams.wrap_content);

    defaultwidth = defaultheight = dip2px(context, default_width);
  }

  public void setdefaultwidth(int defaultwidth) {
    this.defaultwidth = defaultwidth;
  }

  public void setdefaultheight(int defaultheight) {
    this.defaultheight = defaultheight;
  }

  public void setadapter(ninegridadapter adapter) {
    this.adapter = adapter;
    if (adapter == null) {
      return;
    }
    //初始化布局形状
    generatechildrenlayout(adapter.getcount());
    //这里做一个重用view的处理
//    if (oldcount == 0) {
    removeallviews();
    for (int i = 0; i < adapter.getcount(); i++) {
      view itemview = adapter.getview(i, null);
      addview(itemview, generatedefaultlayoutparams());
    }
//    }
     /*else {
      //以前添加过view
      int newviewcount = adapter.getcount();
      if (oldcount > newviewcount) {
        removeviews(newviewcount - 1, oldcount - newviewcount);
        for (int i = 0; i < newviewcount - 1; i++) {
          adapter.getview(i, getchildat(i));
        }
      } else if (oldcount < newviewcount) {
        for (int i = 0; i < newviewcount - oldcount; i++) {
          view itemview = adapter.getview(i, null);
          addview(itemview, generatedefaultlayoutparams());
        }
      }
    }*/

    oldcount = adapter.getcount();
    requestlayout();
  }

  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    super.onmeasure(widthmeasurespec, heightmeasurespec);
    int widthmode = measurespec.getmode(widthmeasurespec);
    int heightmode = measurespec.getmode(heightmeasurespec);
    int sizewidth = measurespec.getsize(widthmeasurespec);
    int sizeheight = measurespec.getsize(heightmeasurespec);
    totalwidth = sizewidth - getpaddingleft() - getpaddingright();
    if (adapter != null && adapter.getcount() > 0) {
      int measurewidth, measureheight;
      int childrencount = adapter.getcount();
      if (childrencount == 1) {
        singlewidth = defaultwidth;
        singleheight = defaultheight;
      } else {
        singlewidth = (totalwidth - gap * (3 - 1)) / 3;
        singleheight = singlewidth;
      }
      measurechildren(measurespec.makemeasurespec(singlewidth, measurespec.exactly),
          measurespec.makemeasurespec(singleheight, measurespec.exactly));
      measurewidth = singlewidth * columns + gap * (columns - 1);
      measureheight = singleheight * rows + linespace * (rows - 1);
      setmeasureddimension(sizewidth, measureheight);
    }
  }

  @override
  protected void onlayout(boolean changed, int l, int t, int r, int b) {

    layoutchildrenview();
  }

  private void layoutchildrenview() {
    if (adapter == null || adapter.getcount() == 0) {
      return;
    }
    int childrencount = adapter.getcount();
    for (int i = 0; i < childrencount; i++) {
      int[] position = findposition(i);
      int left = (singlewidth + gap) * position[1] + getpaddingleft();
      int top = (singleheight + linespace) * position[0] + getpaddingtop();
      int right = left + singlewidth;
      int bottom = top + singleheight;
      imageview childrenview = (imageview) getchildat(i);
      if (childrencount == 1) {
        //只有一张图片
        childrenview.setscaletype(imageview.scaletype.fit_center);
      } else {
        childrenview.setscaletype(imageview.scaletype.center_crop);
      }

      final int itemposition = i;
      childrenview.setonclicklistener(new onclicklistener() {
        @override
        public void onclick(view v) {
          if (onitemclicklisterner != null) {
            onitemclicklisterner.onitemclick(v, itemposition);
          }
        }
      });
      childrenview.layout(left, top, right, bottom);
    }
  }


  private int[] findposition(int childnum) {
    int[] position = new int[2];
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < columns; j++) {
        if ((i * columns + j) == childnum) {
          position[0] = i;//行
          position[1] = j;//列
          break;
        }
      }
    }
    return position;
  }

  public int getgap() {
    return gap;
  }

  public void setgap(int gap) {
    this.gap = gap;
  }

  /**
   * 根据图片个数确定行列数量
   * 对应关系如下
   * num	row	column
   * 1	  1	1
   * 2	  1	2
   * 3	  1	3
   * 4	  2	2
   * 5	  2	3
   * 6	  2	3
   * 7	  3	3
   * 8	  3	3
   * 9	  3	3
   *
   * @param length
   */
  private void generatechildrenlayout(int length) {
    if (length <= 3) {
      rows = 1;
      columns = length;
    } else if (length <= 6) {
      rows = 2;
      columns = 3;
      if (length == 4) {
        columns = 2;
      }
    } else {
      rows = 3;
      columns = 3;
    }
  }

  /**
   * dp to px
   */
  public static int dip2px(context context, double dpvalue) {
    final float scale = context.getresources().getdisplaymetrics().density;
    return (int) (dpvalue * scale + 0.5f);
  }

  public void setonitemclicklisterner(onitemclicklisterner onitemclicklisterner) {
    this.onitemclicklisterner = onitemclicklisterner;
  }

  public interface onitemclicklisterner {
    public void onitemclick(view view, int position);
  }

}
package com.wd.weidologin.home;

import androidx.appcompat.app.appcompatactivity;
import androidx.recyclerview.widget.gridlayoutmanager;
import androidx.recyclerview.widget.recyclerview;

import android.content.broadcastreceiver;
import android.content.context;
import android.content.intent;
import android.content.intentfilter;
import android.content.sharedpreferences;
import android.graphics.color;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.view.viewgroup;
import android.widget.imageview;
import android.widget.toast;

import com.bumptech.glide.glide;
import com.google.gson.gson;
import com.wd.weidologin.r;
import com.wd.weidologin.adapter.attentionrequestadapter;
import com.wd.weidologin.okutil.okre;
import com.wd.weidologin.pic.ninegridadapter;
import com.wd.weidologin.pic.ninegridlayout;

import java.util.arraylist;
import java.util.hashmap;
import java.util.list;

public class mainactivity2 extends appcompatactivity {
  private recyclerview ry;
  private attentionrequestadapter attentionrequestadapter;
  private arraylist<circlebean.resultentity> lists=new arraylist<>();
  private ninegridlayout mgv;
  private circlebean.resultentity result;
  private string picture;
  private list<string> list = new arraylist<string>();
  private adapter adapter;
  public static final string action ="com.example.casts";
  private string msg;
  private sharedpreferences canfig;
  private sharedpreferences.editor edited;
  private string imageurl = "http://pic1.nipic.com/2008-09-08/200898163242920_2.jpg";//如果没有接口可以用这个简单代替这个就不需要进行切割了

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main2);
    init();//(有接口的情况)
    
     list.add(imageurl);//没有接口的情况 ---====================
     if (adapter == null){
      adapter = new adapter(this,list);
      mgv.setadapter(adapter);
    }

    mgv.setonitemclicklisterner(new ninegridlayout.onitemclicklisterner() {
      @override
      public void onitemclick(view view, int position) {
        toast.maketext(getapplicationcontext(), string.valueof(position),toast.length_long).show();
      }
    });//没有接口的情况 ---====================不要混


  }
  private void init() {
    // int sickcircleid = getintent().getintextra("sickcircleid", 0);
    canfig = getsharedpreferences("canfig", context.mode_private);
    edited = canfig.edit();
    int resultkey = canfig.getint("resultkey", 0);

    string url="http:....."+resultkey;
    hashmap<string, string> headmap = new hashmap<>();
    headmap.put("userid","287");
    headmap.put("sessionid","1604985492394287");
    okre.getinstance().getcircledetails(url,headmap, new okre.netcallback() {

      @override
      public void onsuccess(string string) {
        circlebean circlebean = new gson().fromjson(string, circlebean.class);
        picture = circlebean.getresult().getpicture();
        toast.maketext(mainactivity2.this, picture+"", toast.length_short).show();
        mgv = findviewbyid(r.id.d);
        string[] split = picture.split(",");//一般多图上传后需要将图片进行切割
        if (picture.equals("")){//在这里我进行了是否有图片的判断以免没有图片还进行占位
          mgv.setvisibility(view.gone);
        }
        for (int i = 0; i < split.length; i++) {
          list.add(split[i]);
        }
        if (adapter == null){
          adapter = new adapter(mainactivity2.this,list);
          mgv.setadapter(adapter);
        }

        mgv.setonitemclicklisterner(new ninegridlayout.onitemclicklisterner() {图片点击事件
          @override
          public void onitemclick(view view, int position) {
            toast.maketext(getapplicationcontext(), string.valueof(position),toast.length_long).show();
          }
        });
      }

      @override
      public void onfail(string string) {
        // toast.maketext(mainactivity.this, string+"", toast.length_short).show();
      }
    });

  }


  private class adapter extends ninegridadapter {//适配器

    public adapter(context context, list list){
      super(context,list);
    }

    @override
    public int getcount() {
      return list == null?0:list.size();
    }

    @override
    public string geturl(int positon) {
      return getitem(positon) == null ? null : getitem(positon).tostring();
    }

    @override
    public object getitem(int position) {
      return (list == null) ? null : list.get(position);
    }

    @override
    public long getitemid(int position) {
      return position;
    }

    @override
    public view getview(int i, view view) {

      imageview imageview = new imageview(getapplicationcontext());
      viewgroup.layoutparams lp = new viewgroup.layoutparams(viewgroup.layoutparams.wrap_content,
          viewgroup.layoutparams.wrap_content);

      imageview.setscaletype(imageview.scaletype.center_crop);
      imageview.setbackgroundcolor(color.parsecolor("#f5f5f5"));
      imageview.setlayoutparams(lp);
      glide.with(context).load(geturl(i)).into(imageview);
      return imageview;
    }
  }
}

最后因为这个包含网络请求所以需要进行设置
在res下创建xml文件夹创建network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <base-config cleartexttrafficpermitted="true" />
</network-security-config>

放到

在这里插入图片描述

并且添加网络权限

<uses-permission android:name="android.permission.internet" />

网路请求请看以往博客 多图上传请看以往博客或者我上传的代码,后续我会将全部整合上传demo
感谢观看

到此这篇关于android 多图上传后将图片进行九宫格展示的文章就介绍到这了,更多相关android 多图展示九宫格内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
Copyright © 2017-2020  萬仟网 保留所有权利. 粤ICP备17035492号-1