欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

详解android写一个选择图片的示例代码

程序员文章站 2024-02-22 21:08:34
可以达到的效果 第一个图片的位置放照相机,点击打开照相机 其余的是显示全部存储的图片,点击一次是查看大图,长按则是每张图片出现一个checkbox,可以进行...

可以达到的效果

  • 第一个图片的位置放照相机,点击打开照相机
  • 其余的是显示全部存储的图片,点击一次是查看大图,长按则是每张图片出现一个checkbox,可以进行选择

下面是实例效果图

详解android写一个选择图片的示例代码

mainactivity 类

public class mainactivity extends appcompatactivity implements adapterview.onitemclicklistener, adapterview.onitemlongclicklistener, imageadapter.onimagechecklistener, view.onclicklistener {

  private static final int camera_code = 12;
  list<file> filelist = new arraylist<>();
  imageadapter adapter;

  gridview gvimage;
  textview tvfinish;


  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    initview();
    //弹出对话框,加载数据
    loaddata();
  }

  private void initview() {
    gvimage = (gridview) findviewbyid(r.id.gv_image);
    tvfinish = (textview) findviewbyid(r.id.tv_finish);


    adapter = new imageadapter(this, filelist);
    adapter.setonimagechecklistener(this);
    gvimage.setadapter(adapter);
    gvimage.setonitemclicklistener(this);
    gvimage.setonitemlongclicklistener(this);

    tvfinish.setonclicklistener(this);
  }

  private progressdialog showprogressdialog() {
    //弹出对话框
    progressdialog dialog = new progressdialog(this);
    dialog.settitle("提示");
    dialog.setmessage("正在加载图片,请稍等。。。");
    dialog.show();
    return dialog;
  }

  private void loaddata() {
    final progressdialog dialog = showprogressdialog();
    //开启线程
    new thread() {
      @override
      public void run() {
        super.run();
        //递归
        //从sd卡中获取所有图片
        getfile(environment.getexternalstoragedirectory());
        runonuithread(new runnable() {
          @override
          public void run() {
            dialog.dismiss();
            adapter.notifydatasetchanged();
          }
        });
      }
    }.start();
  }

  public void getfile(file dir) {
    //1. 获取子目录
    file[] files = dir.listfiles();
    if (files == null)
      return;
    //集合或者数组去点for
    for (file file : files) {
      if (file.isdirectory())
        getfile(file);
      else {
        //加载图片
        if (file.getname().endswith(".png") || file.getname().endswith(".jpg")) {
          filelist.add(file);
        }
      }

    }
  }

  file camerafile;

  //点击
  @override
  public void onitemclick(adapterview<?> parent, view view, int position, long id) {
    if (position == 0) {
      //getabsolutepath返回的路径是没有"/"
      camerafile = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/dcim/" + system.currenttimemillis() + ".png");
      //打开照相机
      intent intent = new intent(mediastore.action_image_capture);
      //照相机需要带数据
      intent.putextra(mediastore.extra_output, uri.fromfile(camerafile));
      startactivityforresult(intent, camera_code);
    } else {
      //打开大图
      file file = filelist.get(position - 1);
      //带数据跳转到现实大图
      intent intent = new intent(this, showbigimage.class);
      intent.putextra("file", file);
      startactivity(intent);
    }
  }


  @override
  protected void onactivityresult(int requestcode, int resultcode, intent data) {
    super.onactivityresult(requestcode, resultcode, data);
    log.e("tag", resultcode + "---------------------");
    if (requestcode == camera_code && resultcode == result_ok) {
      log.e("tag", (camerafile.exists()) + "");
      filelist.add(0, camerafile);
      adapter.notifydatasetchanged();
    }
  }

  //长按
  @override
  public boolean onitemlongclick(adapterview<?> parent, view view, int position, long id) {
    if (position == 0)
      return false;
    else {
      adapter.open(position);
    }
    return true;
  }

  @override
  public void onimagecheck(boolean b) {
    //b代表 适配器中 有没有勾选的值
    tvfinish.setenabled(b);

  }

  @override
  public void onclick(view v) {
    //需要知道有哪些数据被选中
    //不能使用泛型,arraylist才实现了序列化,list没有实现
    arraylist<file> resultlist = new arraylist<>();
    //通过适配器中的 为true的 选中的项来加载file
    sparsebooleanarray booleanarray = adapter.getbooleanarray();
    for (int i = 0; i < booleanarray.size(); i++) {
      boolean ischeck = booleanarray.get(booleanarray.keyat(i));
      if (ischeck) {
        int position = booleanarray.keyat(i);
        resultlist.add(filelist.get(position - 1));
      }
    }
    intent intent = new intent();
    intent.putextra("list", resultlist);
    //返回数据
    setresult(result_ok, intent);
    finish();
  }
}

imageadapter 类

public class imageadapter extends listitemadapter<file> {

  private boolean select = false;


  public void open(int posisiont) {
    select = true;
    booleanarray.put(posisiont, true);
    if (onimagechecklistener != null)
      onimagechecklistener.onimagecheck(true);
    this.notifydatasetchanged();
  }

  public void close() {
    select = false;
    booleanarray.clear();
    notifydatasetchanged();
  }

  //position
  //hashmap<integer, boolean> map = new hashmap<>();

  private sparsebooleanarray booleanarray = new sparsebooleanarray();

  public sparsebooleanarray getbooleanarray() {
    return booleanarray;
  }

  public imageadapter(context context, list<file> list) {
    super(context, list);
  }

  @override
  public int getcount() {
    //多出来的就是照相机
    return super.getcount() + 1;
  }

  //  @override
//  public view getview(int position, view convertview, viewgroup parent) {
//    if (convertview == null) {
//      imageview iv = new imageview(mcontext);
//      iv.setscaletype(imageview.scaletype.center_crop);
//      iv.setbackgroundcolor(color.argb(0xff, 0x07, 0x05, 0x18));
//      int width = mcontext.getresources().getdisplaymetrics().widthpixels / 3 - 2;
//      gridview.layoutparams params = new gridview.layoutparams(width, width);
//      iv.setpadding(2, 2, 2, 2);
//      iv.setlayoutparams(params);
//      convertview = iv;
//    }
//    imageview iv = (imageview) convertview;
//    if (position == 0) {
//      //照相机
//      iv.setimageresource(r.mipmap.camera);
//    } else {
//      iv.setimageuri(uri.fromfile(getitem(position - 1)));
//    }
//    return convertview;
//  }
  @override
  public view getview(final int position, view convertview, viewgroup parent) {
    viewholder holder;
    if (convertview == null) {
      convertview = view.inflate(mcontext, r.layout.item_image, null);
      holder = new viewholder(convertview);
      convertview.settag(holder);
    } else {
      holder = (viewholder) convertview.gettag();
    }
    if (position == 0) {
      holder.image.setimageresource(r.mipmap.camera);
      holder.checkbox.setvisibility(view.gone);
    } else {
      holder.image.setimageuri(uri.fromfile(getitem(position - 1)));
      if (select) {
        holder.checkbox.setvisibility(view.visible);
        //当前的需不需要勾选呢
        //null
        boolean b = booleanarray.get(position);
        if (b == null || b == false) {
          holder.checkbox.setchecked(false);
        } else {
          holder.checkbox.setchecked(true);
        }
        //item点击和布局冲突
        holder.checkbox.setonclicklistener(new view.onclicklistener() {
          @override
          public void onclick(view v) {
            boolean b = booleanarray.get(position);
            if (b == null || b == false)
              b = true;
            else
              b = false;
            booleanarray.put(position, b);
            //判断所有的boolean,如果已经没有一个true 关闭
            for (int i = 0; i < booleanarray.size(); i++) { //4-true 0==false
              //两个值 key -- > 3 4
              // 0 1 2 3 4 5
              boolean ischecked = booleanarray.get(booleanarray.keyat(i));
              log.e("tag", "----" + ischecked);
              log.e("tag", booleanarray.tostring());
              if (ischecked) {
                //有被勾选的值
                if (onimagechecklistener != null)
                  onimagechecklistener.onimagecheck(true);
                return;
              }
            }
            if (onimagechecklistener != null)
              onimagechecklistener.onimagecheck(false);
            //没有被勾选的值了
            //关闭
            close();
          }
        });
      } else {
        holder.checkbox.setvisibility(view.gone);
      }
      //不能使用oncheck
//      holder.checkbox.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() {
//        @override
//        public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) {
//          booleanarray.put(position, ischecked);
//        }
//      });
    }
    return convertview;
  }


  //回调方法。
  //写在需要执行方法的地方
  //他实现 在需要返回的地方
  public interface onimagechecklistener {
    public void onimagecheck(boolean b);
  }

  private onimagechecklistener onimagechecklistener;

  //alt+insert

  public void setonimagechecklistener(onimagechecklistener onimagechecklistener) {
    this.onimagechecklistener = onimagechecklistener;
  }

  class viewholder {
    imageview image;
    checkbox checkbox;

    public viewholder(view convertview) {
      image = (imageview) convertview.findviewbyid(r.id.iv_image);
      int width = mcontext.getresources().getdisplaymetrics().widthpixels / 3 - 2;
      relativelayout.layoutparams params = new relativelayout.layoutparams(width, width);
      image.setlayoutparams(params);
      checkbox = (checkbox) convertview.findviewbyid(r.id.cb_check);
    }


  }
}

listitemadapter类

//也可以用 extends 来限制一个泛型的父类
//在类的后面定义一个泛型
public abstract class listitemadapter<t> extends baseadapter {

  protected context mcontext;
  protected list<t> mlist;

  //必须要有上下文,数据
  //list<file> list<string>
  public listitemadapter(context context, list<t> list) {
    mcontext = context;
    mlist = list;
  }

  //适配器去加载一个list
  public void setlist(list<t> list) {
    this.mlist = list;
    notifydatasetchanged();
  }

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

  @override
  public t getitem(int position) {
    return mlist.get(position);
  }

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

showbigimage 类

public class showbigimage extends appcompatactivity {


  @override
  protected void oncreate(@nullable bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    imageview iv = new imageview(this);
    file file = (file) getintent().getserializableextra("file");
    iv.setimageuri(uri.fromfile(file));
    setcontentview(iv);
  }
}

main_xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context="com.example.administrator.imageselector.mainactivity">

  <relativelayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@color/colorprimary">

    <textview
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerinparent="true"
      android:text="选取图片"
      android:textcolor="@android:color/white"
      android:textsize="18sp" />

    <textview
      android:id="@+id/tv_finish"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignparentright="true"
      android:layout_centervertical="true"
      android:layout_marginright="10dp"
      android:enabled="false"
      android:text="完成"
      android:textcolor="@color/textenable" />
  </relativelayout>

  <gridview
    android:id="@+id/gv_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:horizontalspacing="2dp"
    android:numcolumns="3"
    android:verticalspacing="2dp" />
</linearlayout>

item_image.xml

<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#03030a">

  <imageview
    android:id="@+id/iv_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:scaletype="centercrop"
    android:src="@mipmap/camera" />

  <checkbox
    android:id="@+id/cb_check"
    android:button="@null"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:background="@drawable/cb_selector"
    android:layout_alignparentright="true"
    android:layout_margin="10dp"
    />

</relativelayout>

res下color文件夹下的textenable.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@android:color/white" android:state_enabled="true" />
  <item android:color="@android:color/darker_gray" android:state_enabled="false" />
</selector>

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