钢镚儿冲刺一周期第八天
一、说在前面
昨天完成了图片的读取,没遇到什么大问题,主要就是时间太紧张忘记更新代码了,连着昨天的份全部放在今天了。
今天打算将图片读取这部分全部完成。
二、代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.imgpicker.Adapter.ResultImageAdapter; import com.example.imgpicker.domain.ImageItem; import com.example.imgpicker.utils.PickerConfig; import java.util.List; @RequiresApi(api = Build.VERSION_CODES.M) public class MainActivity extends AppCompatActivity implements PickerConfig.OnImageSelectFinishListener { private static final int MAX_SELECTED_COUNT = 9; private static final String TAG = "MainActivity"; private static final int PERMISSION_REQUEST_CODE = 1; RecyclerView result_list; ResultImageAdapter resultImageAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); checkPermission(); initPickerConfig(); } private void initView() { result_list = findViewById(R.id.result_list); resultImageAdapter = new ResultImageAdapter(); result_list.setAdapter(resultImageAdapter); } private void initPickerConfig() { PickerConfig picker=PickerConfig.getInstance(); //设置最大值 picker.setMaxSelectedCount(MAX_SELECTED_COUNT); picker.setOnImageSelectFinishListener(this); } private void checkPermission() { int readExStoragePermissionRest = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE); if (readExStoragePermissionRest!= PackageManager.PERMISSION_GRANTED){ //没有权限 requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode==PERMISSION_REQUEST_CODE){ if (grantResults.length==0&&grantResults[0]== PackageManager.PERMISSION_GRANTED) { //有权限 }else { //没有权限 //根据交互去处理 } } } public void pickImgs(View view){ // 打开另外一个界面 startActivity(new Intent(this,PickerAvtivity.class)); } @Override public void onSelectedFinished(List<ImageItem> result) { //返回来的数据显示出来 // for (ImageItem imageItem : result) { // Log.d(TAG, " item----> "+imageItem); // } int horizentalCount; if(result.size()<3){ horizentalCount=result.size(); }else { horizentalCount=3; } result_list.setLayoutManager(new GridLayoutManager(this,horizentalCount)); resultImageAdapter.setData(result,horizentalCount); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.loader.app.LoaderManager; import androidx.loader.content.CursorLoader; import androidx.loader.content.Loader; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.imgpicker.Adapter.ImageListAdapter; import com.example.imgpicker.domain.ImageItem; import com.example.imgpicker.utils.PickerConfig; import java.util.ArrayList; import java.util.List; //D/PickerAvtivity: onCreate: ==================================== //D/PickerAvtivity: _id ==== 43 //D/PickerAvtivity: _data ==== /storage/emulated/0/DCIM/Camera/IMG_20200420_064425.jpg //D/PickerAvtivity: _size ==== 197214 //D/PickerAvtivity: _display_name ==== IMG_20200420_064425.jpg //D/PickerAvtivity: mime_type ==== image/jpeg //D/PickerAvtivity: title ==== IMG_20200420_064425 //D/PickerAvtivity: date_added ==== 1587365066 //D/PickerAvtivity: date_modified ==== 1587365066 //D/PickerAvtivity: description ==== null //D/PickerAvtivity: picasa_id ==== null //D/PickerAvtivity: isprivate ==== null //D/PickerAvtivity: latitude ==== 37.422 //D/PickerAvtivity: longitude ==== -122.084 //D/PickerAvtivity: datetaken ==== 1587365065974 //D/PickerAvtivity: orientation ==== 0 //D/PickerAvtivity: mini_thumb_magic ==== null //D/PickerAvtivity: bucket_id ==== -1739773001 //D/PickerAvtivity: bucket_display_name ==== Camera //D/PickerAvtivity: width ==== 960 //D/PickerAvtivity: height ==== 1280 //D/PickerAvtivity: onCreate: ==================================== public class PickerAvtivity extends AppCompatActivity implements ImageListAdapter.OnItemSelectedChangeListener { private static final String TAG = "PickerAvtivity"; public static final int LOADER_ID=1; private List<ImageItem> mImageItem=new ArrayList<>(); ImageListAdapter mImageListAdapter; TextView finishView; PickerConfig picker; ImageView backView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_picker); // ContentResolver contentResolver=getContentResolver(); // Uri imageUri= MediaStore.Images.Media.EXTERNAL_CONTENT_URI; // Cursor query =contentResolver.query(imageUri,null,null,null,null); // String[] colunmNames=query.getColumnNames(); // while (query.moveToNext()){ // Log.d(TAG, "onCreate: ===================================="); // for (String colunmName : colunmNames) { // Log.d(TAG, colunmName+" ==== "+query.getString(query.getColumnIndex(colunmName))); // } // Log.d(TAG, "onCreate: ===================================="); // } // query.close(); initLoaderManager(); initView(); initEvent(); initConfig(); } private void initConfig() { picker = PickerConfig.getInstance(); int maxSelectedCount= picker.getMaxSelectedCount(); mImageListAdapter.setmMaxSelectedCount(maxSelectedCount); } private void initEvent() { mImageListAdapter.setOnItemSelectedChangeListener(this); finishView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取所选择的数据 List<ImageItem> results = mImageListAdapter.getmSelectedItems(); //通知其他地方 PickerConfig.OnImageSelectFinishListener onImageSelectFinishListener = picker.getmImageSelectedFinishListener(); if (onImageSelectFinishListener!=null){ onImageSelectFinishListener.onSelectedFinished(results); } //结束 finish(); } }); backView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } private void initView() { finishView = findViewById(R.id.finish_tv); RecyclerView listView=findViewById(R.id.image_list_view); backView = findViewById(R.id.back_press_iv); listView.setLayoutManager(new GridLayoutManager(this,3)); //设置适配器 mImageListAdapter = new ImageListAdapter(); listView.setAdapter(mImageListAdapter); } private void initLoaderManager() { mImageItem.clear(); LoaderManager loaderManager=LoaderManager.getInstance(this); loaderManager.initLoader(LOADER_ID, null, new LoaderManager.LoaderCallbacks<Cursor>() { @NonNull @Override public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) { if(id==LOADER_ID){ return new CursorLoader(PickerAvtivity.this,MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{"_data","_display_name","date_added"}, null,null,"date_added DESC"); } return null; } @Override public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) { if (cursor!=null){ while (cursor.moveToNext()){ String path=cursor.getString(0); String title=cursor.getString(1); long date=cursor.getLong(2); ImageItem imageItem=new ImageItem(path,title,date); mImageItem.add(imageItem); } cursor.close(); for (ImageItem imageItem : mImageItem) { Log.d(TAG, "imageItem ==========> "+imageItem.toString()); } mImageListAdapter.setData(mImageItem); } } @Override public void onLoaderReset(@NonNull Loader<Cursor> loader) { } }); } @Override public void OnItemSelectedChange(List<ImageItem> mSelectedItems) { //所选择的数据发生变化 finishView.setText("("+mSelectedItems.size()+"/"+mImageListAdapter.getmMaxSelectedCount()+")完成"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker.utils; import com.example.imgpicker.domain.ImageItem; import java.util.List; public class PickerConfig { private PickerConfig(){}; private static PickerConfig spickerConfig; public static PickerConfig getInstance(){ if(spickerConfig==null){ spickerConfig=new PickerConfig(); } return spickerConfig; } private OnImageSelectFinishListener mImageSelectedFinishListener=null; private int maxSelectedCount=1; public int getMaxSelectedCount() { return maxSelectedCount; } public void setMaxSelectedCount(int maxSelectedCount) { this.maxSelectedCount = maxSelectedCount; } public OnImageSelectFinishListener getmImageSelectedFinishListener() { return mImageSelectedFinishListener; } public void setOnImageSelectFinishListener(OnImageSelectFinishListener listener){ this.mImageSelectedFinishListener=listener; } public interface OnImageSelectFinishListener{ void onSelectedFinished(List<ImageItem> result); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker.utils; import android.content.Context; import android.graphics.Point; import android.view.WindowManager; public class SizeUtils { public static Point getScreenSize(Context context){ Point point=new Point(); ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point); return point; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker.domain; public class ImageItem { private String path; private String title; private long date; public ImageItem(String path, String title, long date) { this.path = path; this.title = title; this.date = date; } @Override public String toString() { return "ImageItem{" + "path='" + path + '\'' + ", title='" + title + '\'' + ", date=" + date + '}'; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker.Adapter; import android.graphics.Point; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.imgpicker.R; import com.example.imgpicker.domain.ImageItem; import com.example.imgpicker.utils.SizeUtils; import java.util.ArrayList; import java.util.List; public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.InnerHolder> { private List<ImageItem> mImageItems=new ArrayList<>(); private List<ImageItem> mSelectedItems =new ArrayList<>(); private OnItemSelectedChangeListener mOnItemSelectedChangeListener=null; private static final int MAX_SELECTED_COUNT = 9; private int mMaxSelectedCount= MAX_SELECTED_COUNT; public List<ImageItem> getmSelectedItems() { return mSelectedItems; } public void setmSelectedItems(List<ImageItem> mSelectedItems) { this.mSelectedItems = mSelectedItems; } public int getmMaxSelectedCount() { return mMaxSelectedCount; } public void setmMaxSelectedCount(int mMaxSelectedCount) { this.mMaxSelectedCount = mMaxSelectedCount; } @NonNull @Override public ImageListAdapter.InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { //加载itemView View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false); Point point = SizeUtils.getScreenSize(itemView.getContext()); RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(point.x/3,point.x/3); itemView.setLayoutParams(layoutParams); return new InnerHolder(itemView); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onBindViewHolder(@NonNull ImageListAdapter.InnerHolder holder, int position) { //绑定数据 final View itemView = holder.itemView; ImageView imageView = holder.itemView.findViewById(R.id.image_iv); final View imageCover=itemView.findViewById(R.id.image_cover); final CheckBox checkBox=itemView.findViewById(R.id.image_check_box); final ImageItem imageItem = mImageItems.get(position); Glide.with(imageView.getContext()).load(imageItem.getPath()).into(imageView); //根据状态显示数据 //解决复用显示问题 if(mSelectedItems.contains(imageItem)){ //包含则设置成选上 checkBox.setChecked(true); checkBox.setButtonDrawable(itemView.getContext().getDrawable(R.mipmap.checked)); imageCover.setVisibility(View.VISIBLE); }else { //没有则设置成未选上 checkBox.setChecked(false); checkBox.setButtonDrawable(itemView.getContext().getDrawable(R.mipmap.unchecked)); imageCover.setVisibility(View.GONE); } itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //是否选择上 //如果选择上则取消 //如果没有则选上 if(mSelectedItems.contains(imageItem)){ //已经选择上了,则取消 mSelectedItems.remove(imageItem); //修改UI checkBox.setChecked(false); checkBox.setButtonDrawable(itemView.getContext().getDrawable(R.mipmap.unchecked)); imageCover.setVisibility(View.GONE); }else { //没有选择上,则选上,先判断是否超过最大值 if(mSelectedItems.size()>=mMaxSelectedCount){ Toast toast = Toast.makeText(checkBox.getContext(), null, Toast.LENGTH_SHORT); toast.setText("最多可以选择"+mMaxSelectedCount+"张图片"); toast.show(); return; } mSelectedItems.add(imageItem); //修改UI checkBox.setChecked(true); checkBox.setButtonDrawable(itemView.getContext().getDrawable(R.mipmap.checked)); imageCover.setVisibility(View.VISIBLE); } if (mOnItemSelectedChangeListener!=null){ mOnItemSelectedChangeListener.OnItemSelectedChange(mSelectedItems); } } }); } public void setOnItemSelectedChangeListener(OnItemSelectedChangeListener listener){ this.mOnItemSelectedChangeListener=listener; } //暴露一个接口给activity来判断选择 public interface OnItemSelectedChangeListener{ void OnItemSelectedChange(List<ImageItem> mSelectedItems); } @Override public int getItemCount() { return mImageItems.size(); } public void setData(List<ImageItem> mImageItem) { mImageItems.clear(); mImageItems.addAll(mImageItem); notifyDataSetChanged(); } public class InnerHolder extends RecyclerView.ViewHolder { public InnerHolder(@NonNull View itemView) { super(itemView); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.imgpicker.Adapter; import android.graphics.Point; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.imgpicker.R; import com.example.imgpicker.domain.ImageItem; import com.example.imgpicker.utils.SizeUtils; import java.util.ArrayList; import java.util.List; public class ResultImageAdapter extends RecyclerView.Adapter<ResultImageAdapter.InnerHolder> { private List<ImageItem> mImageItems=new ArrayList<>(); private int horizentalCount=1; @NonNull @Override public ResultImageAdapter.InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false); itemView.findViewById(R.id.image_check_box).setVisibility(View.GONE); return new InnerHolder(itemView); } @Override public void onBindViewHolder(@NonNull ResultImageAdapter.InnerHolder holder, int position) { View itemView = holder.itemView; Point point = SizeUtils.getScreenSize(itemView.getContext()); RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(point.x/horizentalCount,point.x/horizentalCount); itemView.setLayoutParams(layoutParams); ImageView imageView =itemView.findViewById(R.id.image_iv); ImageItem imageItem = mImageItems.get(position); Glide.with(imageView.getContext()).load(imageItem.getPath()).into(imageView); } @Override public int getItemCount() { return mImageItems.size(); } public void setData(List<ImageItem> result, int horizentalCount) { this.horizentalCount=horizentalCount; mImageItems.clear(); mImageItems.addAll(result); notifyDataSetChanged(); } public class InnerHolder extends RecyclerView.ViewHolder { public InnerHolder(@NonNull View itemView) { super(itemView); } } }
三、效果
四、个人体会
今天的收获很多,跟着up主学习了写自己的接口,发现接口确实对安全性起着至关重要的作用也刷新了我对接口的认识。之前认为接口只是一个函数,我告诉你调用这个函数出来的答案是什么你才会使用,原来并不是这么简单。另外看着up主调试bug自己也深有体会也学会了一些调bug的技巧。总得说今天这一下午确实么有白肝~