带图片数量限制的相册选择
这个页面会返回一个key为images 的arraylist 给打开它的页面
Adapter的layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/image"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="match_parent"
android:scaleType="fitXY"
android:layout_height="100dp">
</ImageView>
<TextView
android:id="@+id/select"
app:layout_constraintTop_toTopOf="@+id/image"
app:layout_constraintRight_toRightOf="@+id/image"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#5fdbdbdb"
android:src="@drawable/delete"
android:textSize="30sp"
android:gravity="center"
android:text="">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
Adapter
package com.rengda.sigangapp.Adapter
import android.app.Activity
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.media.ThumbnailUtils
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.rengda.kotlinapp.common.AlertDialogUtil
import com.rengda.sigangapp.MyApplication
import com.rengda.sigangapp.MyApplication.Companion.context
import com.rengda.sigangapp.R
import com.rengda.sigangapp.common.MSG
import kotlin.math.max
class AlbumAdapter(val context: Context, val list: ArrayList<Uri>, val maxSize:Int?, val finishButton:Button, val activity:Activity) :RecyclerView.Adapter<AlbumAdapter.ViewHolder>(){
private val selectImageUri= linkedMapOf<Int,Int>() //记录选择的图片的下标
private val selectIndexHashMap= hashMapOf<Int,Boolean>()//通过下标来记录图片的选中状态
val selectColor=Color.parseColor("#8BC34A")
val diselectColor=Color.parseColor("#dbdbdb")
inner class ViewHolder(view: View):RecyclerView.ViewHolder(view){
val image: ImageView =view.findViewById(R.id.image)
val select:TextView=view.findViewById(R.id.select)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view=LayoutInflater.from(parent.context).inflate(R.layout.item_album_image,parent,false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//holder.image.setImageBitmap(getBitMapByUri(list[position]))//显示图片
Glide.with(context).load(list[position]).into(holder.image);
//显示选中情况
if (selectIndexHashMap[position]==true){
holder.select.setBackgroundColor(selectColor)
}else{
holder.select.setBackgroundColor(diselectColor)
}
//点击图片右上角的选择框
holder.select.setOnClickListener {
var selectButtonColor:Int
var finishButtonColor:Int
if( selectIndexHashMap[position]==true) {//点击之后不被选中
selectButtonColor=diselectColor
selectImageUri.remove(position)//移走
selectIndexHashMap[position]=false //设置为不选中
//完成按钮的颜色
if (selectImageUri.size==0) {//一条都没选中了
finishButtonColor=diselectColor
}else{
finishButtonColor=selectColor
}
}else{//点击之后选中
finishButtonColor=selectColor //点选中肯定完成按钮要变绿
if (maxSize!=null){ //有设置最大数量
if (selectImageUri.size< maxSize){
selectButtonColor=selectColor
selectImageUri[position]=position//加入
selectIndexHashMap[position]=true //设置为不选中
}else{
selectButtonColor=diselectColor
}
}else {
selectButtonColor = selectColor
selectImageUri[position] = position//加入
selectIndexHashMap[position] = true //设置为不选中
}
}
holder.select.setBackgroundColor(selectButtonColor)//选中框设置颜色
finishButton.setBackgroundColor(finishButtonColor)//选中框设置为灰色
//按钮显示的内容
if (selectImageUri.size==0){ //一条都没选
finishButton.setText("完成")
}else if (maxSize==null){ //没上限
finishButton.setText("完成(${selectImageUri.size})")//完成按钮显示数量
}else{
finishButton.setText("完成(${selectImageUri.size}/${maxSize})")//完成按钮显示数量
}
}
holder.image.setOnClickListener{
AlertDialogUtil.showBigImage(context,list[position])
}
}
override fun getItemCount(): Int {
return list.size
}
//初始化
fun doInit(){
//每张图初始的时候都是不被选择的
for (index in 0 until list.size){//左开右闭区间
selectIndexHashMap[index]=false
}
//关闭当前页面,并把选择的uri传递给上一个页面
}
fun getSelectImage():ArrayList<Uri>{
val imagelist= arrayListOf<Uri>()
for (map in selectImageUri){
imagelist.add(list[map.key])
}
return imagelist
}
//通过uri来获取bitmap
fun getBitMapByUri (uri:Uri):Bitmap?{
val fd = MyApplication.context.contentResolver.openFileDescriptor(uri, "r")
if (fd != null) {
val bitmap = BitmapFactory.decodeFileDescriptor(fd.fileDescriptor)
var scaledBitmap:Bitmap?=null
if (bitmap!=null){
// scaledBitmap= Bitmap.createScaledBitmap(bitmap,80,80,true) //缩放法压缩
//缩放压缩 2/10
var matrix = Matrix()
matrix.setScale(0.2f, 0.2f);
scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
}
// val scaledBitmap= Bitmap.createScaledBitmap(bitmap,80,80,true)
fd.close()
return scaledBitmap
}
return null
}
}
activity的layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".AlbumActivity">
<ImageView
android:id="@+id/headIamge"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@color/mianColor">
</ImageView>
<ImageView
android:id="@+id/cancelButton"
app:layout_constraintTop_toTopOf="@+id/headIamge"
app:layout_constraintLeft_toLeftOf="@+id/headIamge"
app:layout_constraintBottom_toBottomOf="@+id/headIamge"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="@drawable/back">
</ImageView>
<Button
android:id="@+id/finishButton"
app:layout_constraintTop_toTopOf="@+id/headIamge"
app:layout_constraintRight_toRightOf="@+id/headIamge"
app:layout_constraintBottom_toBottomOf="@+id/headIamge"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/light_grey"
android:text="完成"
android:textSize="16sp">
</Button>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
app:layout_constraintTop_toBottomOf="@+id/headIamge"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintVertical_weight="1"
>
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
activity
package com.rengda.sigangapp
import android.Manifest
import android.app.Activity
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.rengda.sigangapp.Adapter.AlbumAdapter
import com.rengda.sigangapp.Adapter.ImageAdapter
import com.rengda.sigangapp.common.MSG
import kotlinx.android.synthetic.main.activity_album.*
import kotlinx.android.synthetic.main.activity_inload_info.*
import kotlinx.android.synthetic.main.activity_inload_info.recyclerView
import retrofit2.http.Url
class AlbumActivity : AppCompatActivity() {
lateinit var imageAdapter: AlbumAdapter
val list= arrayListOf<Uri>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_album)
val context=this;
val gridLayout= GridLayoutManager(this,3);
imageAdapter= AlbumAdapter(context,list,9,finishButton,this)
imageAdapter.doInit()
recyclerView.adapter=imageAdapter
recyclerView.layoutManager=gridLayout
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE),1)
}else{
getAllImageUri()
}
//关闭页面,返回空的arraylist
cancelButton.setOnClickListener{
val intent=Intent()
intent.putExtra("images", arrayListOf<Uri>())
setResult(Activity.RESULT_OK,intent)
finish()//关闭页面
}
//关闭页面并且返回选择的照片的arraylist
finishButton.setOnClickListener{
val list=imageAdapter.getSelectImage()
if (list.size>0){//有选中的 才能从完成退出 否则要去点X才能退出
val intent=Intent()
intent.putExtra("images",imageAdapter.getSelectImage())
setResult(Activity.RESULT_OK,intent)
finish()//关闭页面
}
}
}
//获取相册中全部的图片
fun getAllImageUri(){
val cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
if (cursor != null) {
while (cursor.moveToNext()) {
val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
list.add(uri)
}
cursor.close()
imageAdapter.notifyDataSetChanged()
}
}
//动态权限获取的结果
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when(requestCode){
1->{
if (grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED&&grantResults[1]==PackageManager.PERMISSION_GRANTED){
getAllImageUri()
}else{
MSG.showLongMsg("你拒绝了读取相册的权限!")
}
}
}
}
//其他页面打开这个页面的时候要用这个
companion object{
fun startActivity(context: Activity){
var intent= Intent(context, AlbumActivity::class.java)
context.startActivityForResult(intent,2)
}
}
}
效果图
本文含有隐藏内容,请 开通VIP 后查看