最近在项目中有一个用户反馈的功能中要上传图片,和微信发朋友圈添加图片的功能其实有点类似,所以我想着用GridView来实现这个功能,整个过程也很简单,画不多说,详细步骤见下:
1.先来看MainActivity的布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="48dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:background="@drawable/aty_top_bg">
<TextView android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="图片"/>
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/feedback_et_bg"
>
<GridView
android:id="@+id/grideView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:verticalSpacing="10dp"
>
</GridView>
</RelativeLayout>
</LinearLayout>
非常简单,一个ToolBar+GridView,完事儿了!
2.接下来看下GridView的item的布局:item_published_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:descendantFocusability="blocksDescendants"
android:layout_width="66dp"
android:layout_height="66dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<Button
android:id="@+id/bt_del"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:background="@drawable/bt_dynamic_del" />
</RelativeLayout>
</RelativeLayout>
3.创建Adapter适配器GridViewAddImgesAdpter,在适配器中定义允许添加的最大图片数,int maxImage;
在构造方法中获取传递过来的数据:
public GridViewAddImgesAdpter(List<Map<String, String>> datas, Context context) {
this.datas = datas;
this.context = context;
inflater = LayoutInflater.from(context);
}
在getView方法中对datas进行判断,如果当前position小于datas.size就加载传递过来的uri并加载,否则就加载“加载图片”:
if (datas != null && position < datas.size()) {
String uri = datas.get(position).get("uri");
if (uri == null){
Log.e("adapter uri","adapter uri is null");
}
Uri uri1 = Uri.parse(uri);
// final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(uri1)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
datas.remove(position);
notifyDataSetChanged();
}
});
} else {
Glide.with(context)
.load(R.mipmap.image_add)
.priority(Priority.HIGH)
.centerCrop()
.into(viewHolder.ivimage);
viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.btdel.setVisibility(View.GONE);
}
加载图片这里我使用了Glide,也可以使用其他的加载框架,效果都是一样的,别忘了加上依赖:
implementation 'com.github.bumptech.glide:glide:3.7.0'
对删除按钮的监听也在上面的代码里了,比较简单,大家一看就能明白,这里就不赘述了
至此整个Adapter的代码就基本完成了!
4.接下来就是在MainActivity中写相关的代码,在onCreat中初始化Adapter并给GridView设置Adapter,再给GridView的item设置点击事件,当点击的时候就弹出选择框,跳转至系统相机或者相册:
gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
gridView.setAdapter(gridViewAddImgesAdpter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (position < datas.size()){
String uri = datas.get(position).get("uri");
Log.e("takepic uri","take uri5 :"+Uri.parse(uri));
Intent intent = new Intent(MainActivity.this, ImagePriviewActivity.class);
intent.putExtra("picUri", uri);
startActivity(intent);
}else{
showdialog();
}
}
});
showdialog()方法这里就不贴代码了,各位可以根据自己喜欢的样式自由定制,下面直接贴上拍照和相册选照片的代码
5.调用相机和跳转至相册的方法:
调用相机:
public void takePic() {
File file = new File(IMAGE_DIR);
if (!file.exists()){
file.mkdir();
}
empFile = new File(file,System.currentTimeMillis() + "_" + PHOTO_FILE_NAME);
// Uri uri = Uri.fromFile(empFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", empFile));
// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(empFile));
startActivityForResult(intent, TAKE_PIC);
}
跳转至相册:
public void localPic(){
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,LOCAL_PIC);
}
别忘了在清单文件中加上权限哦!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
6.重写onActivityResult方法,在改方法中将返回的数据进行包装处理并添加到集合中去
if (resultCode == RESULT_OK){
if (requestCode == LOCAL_PIC){//相册
uri = data.getData();
upLoadIamge(uri);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
if ( bitmap != null){
Log.e("null--bitmap1","bitmap1isnull:"+bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == TAKE_PIC){//相机
// uri = Uri.fromFile(empFile);
if (empFile != null){
uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", empFile);
upLoadIamge(uri);
}
}
}
这里需要注意一下,有些编译器的版本不一样,在获取uri的时候方法也不一样,大家可以用Uri.fromFile来获取,如果不行的话就换成下面的方法,如果是用下面的方法的话要注意,还要做如下两步操作:
Manifest中添加如下代码:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
在res下新建xml文件夹并创建provider_paths.xml文件,内容如下:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
7.将uri添加到集合中去,通过构造器传递给Adapter并调用notifyDataSetChanged通知数据的变化:
public void photoUri(String uri) {
if (uri == null){
Log.e("uri","uri is null:"+uri);
}
Map<String,String> map=new HashMap<>();
map.put("uri",uri);
datas.add(map);
gridViewAddImgesAdpter.notifyDataSetChanged();
}
8.以上代码就可以实现调用相机或者相册添加图片至GridView中的功能了,哦,不要忘了 ,最后还有一个点击图片查看原图,其实已经在设置itme监听器的时候已经做了哈
if (position < datas.size()){
String uri = datas.get(position).get("uri");
Log.e("takepic uri","take uri5 :"+Uri.parse(uri));
Intent intent = new Intent(MainActivity.this, ImagePriviewActivity.class);
intent.putExtra("picUri", uri);
startActivity(intent);
}
这就是点击查看预览的方法啦,还要注意一点,这时候要在item的根布局设置android:descendantFocusability="blocksDescendants"属性,不然item的点击事件和删除按钮的点击事件会冲突的哦
9.预览的界面很简单,就是一个ImagePriviewActivity,一个ImageVIew来加载。布局如下:
activity_priview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/color_00"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_priview"
android:layout_width="360dp"
android:layout_height="480dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
ImagePriviewActivity中的代码如下:
Intent intent = getIntent();
if (intent != null){
Uri uri = Uri.parse(intent.getStringExtra("picUri"));
Log.e("takepic uri","take uri6 :"+uri);
Glide.with(this).load(uri).into(imageView);
}
完事儿了!
10.以上就是使用GridView实现仿微信朋友圈添加、删除、预览图片的全部内容,希望能对大家有所帮助,喜欢的话可以帮忙转发点赞,有不足的地方希望大家指出并交流,谢谢大家!