Android 图片选择详解及实例代码

Android 图片选择详解及实例代码,第1张

概述 Android图片选择可以达到的效果:1.第一个图片的位置放照相机,点击打开照相机

 AndroID 图片选择

可以达到的效果:

1.第一个图片的位置放照相机,点击打开照相机

2.其余的是显示全部存储的图片,点击一次是查看大图,长按则是每张图片出现一个checkBox,可以进行选择

下面是实例效果图

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();    //d出对话框,加载数据    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() {    //d出对话框    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,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);//      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,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>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

总结

以上是内存溢出为你收集整理的Android 图片选择详解及实例代码全部内容,希望文章能够帮你解决Android 图片选择详解及实例代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147424.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存