写一个关于
android仿微信图片选择器选取多张照片然后处理这些照片,上传过服务端等!中间有一些定位获取当前地址的功能,小伙伴们应该可以看出来吧!不需要的,直接过滤掉就行了!获取到图片后,本文章对图片进行处理,因为服务器需要转成Base64,这个过程我就没贴出来,需要的小伙伴评论说出我给你贴出来喽,很简单,就一个方法!
进入相册选择图片以GridView显示在界面上
item_dynamic布局 这里我只取了GrideView,
1、布局layout中使用GridView
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#FFFFFF"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="5dp"
android:numColumns="4"
android:padding="8dp"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp" >
</GridView>
2、Activity界面代码
import android.Manifest; import android.app.AlertDialog; import android.app.Dialog; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import list.test.wwy.com.myapplication.R; import list.test.wwy.com.myapplication.adapter.SubmitAdapter; import list.test.wwy.com.myapplication.util.Util;
/**
* Created by wwy on 2017/9/14.
*/
public class InDynamicActivity extends BaseActivity implements View.OnClickListener, RequestUtilPargnacyRecord.DataInfoListener {
private List<Bitmap> data = new ArrayList<Bitmap>(); private GridView mGridView; private SubmitAdapter adapter; private String photoPath; private List<String> imgList = new ArrayList<>(); private static final int REQUEST_PICK = 101; // 需要
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_dynamic);
// 设置默认图片为加号,即点击此图片可以进入相册 add_photo 为默认的一个图片添加的图 Bitmap bp = BitmapFactory.decodeResource(getResources(), R.mipmap.add_photo); data.add(bp); // ID
mGridView = (GridView) findViewById(R.id.gridview); initOclick();// 绑定Adapter adapter = new SubmitAdapter(getApplicationContext(), data, mGridView, 4); mGridView.setAdapter( adapter);
}
private void initOclick() { // 设置点击监听事件 mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (data.size() == 5) { Toast.makeText(this, "图片已满4张", Toast.LENGTH_SHORT).show(); } else { if (position == data.size() - 1) { // 选择图片 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK); } else { // Toast.makeText(InDynamicActivity.this, "点击第" + (position + 1) + " 号图片", Toast.LENGTH_SHORT).show(); } } } }); // 设置长按事件 mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (position != data.size()-1){ dialog(position); } return true; } }); }
/* * Dialog对话框提示用户删除操作 position为删除图片位置 */ protected void dialog(final int position) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("确认移除已添加图片吗?"); builder.setTitle("提示"); builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); data.remove(position); adapter.notifyDataSetChanged(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); }
// 响应startActivityForResult,获取图片路径 @Override protected void onActivityResult(int requestCode, int resultCode, Intent datas) { if (requestCode == REQUEST_PICK && resultCode == RESULT_OK) { if (datas != null) { try { Uri uri = datas.getData(); // 这里开始的第二部分,获取图片的路径: String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = null; if (Build.VERSION.SDK_INT < 11){ cursor = managedQuery(uri, proj, null, null, null); }else { CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null); cursor = cursorLoader.loadInBackground(); } // 这个是获得用户选择的图片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); // 最后根据索引值获取图片路径 photoPath = cursor.getString(column_index); if (!photoPath.equals("") || photoPath != null){ imgList.add(photoPath); } Log.i("photoPath","-----str--------->路径 " + photoPath); Log.i("photoPath","----uri---------->路径 " + Uri.parse(photoPath)); } catch (Exception e) { e.printStackTrace(); } } } }
@Override protected void onResume() { super.onResume(); Log.i("photoPath","--------------> 运行到这里"); if (!TextUtils.isEmpty(photoPath)) { Bitmap newBp = Util.decodeSampledBitmapFromFd(photoPath, 300, 300); data.remove(data.size() - 1); // bg2.setImageBitmap(newBp); Bitmap bp = BitmapFactory.decodeResource(getResources(), R.mipmap.add_photo); data.add(newBp); data.add(bp); //将路径设置为空,防止在手机休眠后返回Activity调用此方法时添加照片 photoPath = null; adapter.notifyDataSetChanged(); if (data.size() == 5){ data.remove(data.size() - 1); } } }
}
注:上面部分代码的封装方法:
decodeSampledBitmapFromFd(photoPath, 300, 300)
public static Bitmap decodeSampledBitmapFromFd(String pathName, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; //避免出现内存溢出的情况,进行相应的属性设置。 options.inPreferredConfig = Bitmap.Config.RGB_565; options.inDither = true; Bitmap src = BitmapFactory.decodeFile(pathName, options); return src; }
calculateInSampleSize(options, reqWidth, reqHeight) 如下:
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
介绍:上面包括主要的显示照片列表的,还有其它的,如:定位当前位置的经纬度和详细地址,用不到的话直接去掉不影响其它的,
3、适配器Adapter
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import com.health.gw.healthhandbook.R;
public class SubmitAdapter extends BaseAdapter {
private Context context; private List<Bitmap> data; private LayoutInflater inflater; private GridView mGridView; private int gridViewH; private int imageViewH; private int number;
public SubmitAdapter(Context context, List<Bitmap> data, GridView mGridView) {
this.context = context; this.data = data; this.mGridView = mGridView; this.number = number; inflater = LayoutInflater.from(context); LayoutParams params = (LayoutParams) mGridView.getLayoutParams(); gridViewH = params.height;}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem( int position) {
return data.get(position);
}
@Override
public long getItemId( int position) {
return position;
}
@Override
public View getView( int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.griditem, null);
holder = new Holder();
holder. imageView = (ImageView) convertView.findViewById(R.id.imageView1);
// 获取到ImageView的显示高度
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder. imageView
.getLayoutParams();
imageViewH = params. height;
convertView.setTag(holder);
} else {
setGridView(); // 注意加上,此方法是让选择回来的图片按照正方形显示,一排显示4个
holder = (Holder) convertView.getTag();
}
// 绑定图片原始尺寸,方便以后应用
holder. imageView.setScaleType(ScaleType. CENTER_CROP);
int[] parameter = { 300, 300 }; holder.imageView.setTag(parameter); holder.imageView.setImageBitmap(data.get(position)); return convertView;
}
private void setGridView() { LayoutParams lp = (LayoutParams) mGridView.getLayoutParams(); if (number == 4){ if (data.size() < 4) { lp.height = gridViewH; } } if (number == 8){ if (data.size() < 4) { lp.height = gridViewH; } else if (data.size() < number) { lp.height = gridViewH * 2 - (gridViewH - imageViewH) / 2; } else { lp.height = gridViewH * 3 - (gridViewH - imageViewH); } } mGridView.setLayoutParams(lp); }
class Holder { private ImageView imageView; }
}
上面的适配器全部都需要,
4、上面还需要一个子布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="80dp"
android:layout_height="80dp"
android:descendantFocusability="blocksDescendants"
android:gravity="center" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="centerCrop"
android:src="@mipmap/newadd" />
</RelativeLayout>
下面几张图片是我的运行图,上面代码我是把图片部分给抽离出来了,主要看效果就行了!
以上就是全部了!小伙伴们有哪里不明白的,可以留言哦!下面是我的样式,不过在上面代码中把除了图片部分其他的代码删除了,因为不是重点吗!!对吧,,哈哈哈哈,,,,今天就到这里了!!!