安卓开发之QQ图片的选择效果

来源:爱站网时间:2020-08-20编辑:网友分享
微信朋友圈或QQ空间中点击图片后会放大图片展示到我们跟前,再点击返回原来的图片,并有放大缩小的按键,下面爱站技术频道小编就为大家带来了安卓开发之QQ图片的选择效果,希望对你有帮助。

微信朋友圈或QQ空间中点击图片后会放大图片展示到我们跟前,再点击返回原来的图片,并有放大缩小的按键,下面爱站技术频道小编就为大家带来了安卓开发之QQ图片的选择效果,希望对你有帮助。

效果展示

布局文件

布局是很简单的,一个GridView,直接上布局:

layout/activity_add_photo.xml

layout/activity_add_photo_gv_items.xml 使用了自定义的view使得布局为正方形

代码实现

SquareRelativeLayout.java:

package com.shenhua.tabhostdemo.selectimg;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 * 自定义方形布局
 * Created by Shenhua on 4/25/2016.
 */
public class SquareRelativeLayout extends RelativeLayout {
 public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 public SquareRelativeLayout(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public SquareRelativeLayout(Context context) {
  super(context);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
  int childWidthSize = getMeasuredWidth();
  widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
  heightMeasureSpec = widthMeasureSpec;
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 }
}

UploadPhotoActivity.java: 主Activity

package com.shenhua.tabhostdemo.selectimg;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shenhua.tabhostdemo.R;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shenhua on 4/25/2016.
 */
public class UploadPhotoActivity extends AppCompatActivity {

 private static final int IMG_COUNT = 8;
 private static final String IMG_ADD_TAG = "a";
 private GridView gridView;
 private GVAdapter adapter;
 private TextView textView;
 private ImageView img;
 private List list;

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_add_photo);
  gridView = (GridView) findViewById(R.id.gridview);
  textView = (TextView) findViewById(R.id.send);
  textView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    System.out.println("发送:" + Integer.toString(list.size() - 1));
    upLoad();
   }
  });
  initData();
 }

 private void upLoad() {
  Bitmap bitmap;
  Bitmap bmpCompressed;
  for (int i = 0; i ();
   list.add(IMG_ADD_TAG);
  }
  adapter = new GVAdapter();
  gridView.setAdapter(adapter);
  gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView> parent, View view, int position, long id) {
    if (list.get(position).equals(IMG_ADD_TAG)) {
     if (list.size() ();
  }
  if (adapter == null) {
   adapter = new GVAdapter();
  }
  adapter.notifyDataSetChanged();
 }

 private class GVAdapter extends BaseAdapter {

  @Override
  public int getCount() {
   return list.size();
  }

  @Override
  public Object getItem(int position) {
   return null;
  }

  @Override
  public long getItemId(int position) {
   return 0;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
   final ViewHolder holder;
   if (convertView == null) {
    convertView = LayoutInflater.from(getApplication()).inflate(R.layout.activity_add_photo_gv_items, parent, false);
    holder = new ViewHolder();
    holder.imageView = (ImageView) convertView.findViewById(R.id.main_gridView_item_photo);
    holder.checkBox = (CheckBox) convertView.findViewById(R.id.main_gridView_item_cb);
    convertView.setTag(holder);
   } else {
    holder = (ViewHolder) convertView.getTag();
   }
   String s = list.get(position);
   if (!s.equals(IMG_ADD_TAG)) {
    holder.checkBox.setVisibility(View.VISIBLE);
    holder.imageView.setImageBitmap(ImageTool.createImageThumbnail(s));
   } else {
    holder.checkBox.setVisibility(View.GONE);
    holder.imageView.setImageResource(R.mipmap.ic_photo_upload);
   }
   holder.checkBox.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     list.remove(position);
     refreshAdapter();
    }
   });
   return convertView;
  }

  private class ViewHolder {
   ImageView imageView;
   CheckBox checkBox;
  }

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (data == null) {
   System.out.println("data null");
   return;
  }
  if (requestCode == 0) {
   final Uri uri = data.getData();
   String path = ImageTool.getImageAbsolutePath(this, uri);
   System.out.println(path);
   if (list.size() == IMG_COUNT) {
    removeItem();
    refreshAdapter();
    return;
   }
   removeItem();
   list.add(path);
   list.add(IMG_ADD_TAG);
   refreshAdapter();
  }
 }

 private void removeItem() {
  if (list.size() != IMG_COUNT) {
   if (list.size() != 0) {
    list.remove(list.size() - 1);
   }
  }
 }

}

ImageTool.java: 图片工具类

package com.shenhua.tabhostdemo.selectimg;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * Created by shenhua on 4/26/2016.
 */
public class ImageTool {

 /**
  * 获取图片的绝对路径,需要添加用户权限
  */
 @TargetApi(19)
 public static String getImageAbsolutePath(Activity context, Uri imageUri) {
  if (context == null || imageUri == null)
   return null;
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
   if (isExternalStorageDocument(imageUri)) {
    String docId = DocumentsContract.getDocumentId(imageUri);
    String[] split = docId.split(":");
    String type = split[0];
    if ("primary".equalsIgnoreCase(type)) {
     return Environment.getExternalStorageDirectory() + "/" + split[1];
    }
   } else if (isDownloadsDocument(imageUri)) {
    String id = DocumentsContract.getDocumentId(imageUri);
    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    return getDataColumn(context, contentUri, null, null);
   } else if (isMediaDocument(imageUri)) {
    String docId = DocumentsContract.getDocumentId(imageUri);
    String[] split = docId.split(":");
    String type = split[0];
    Uri contentUri = null;
    if ("image".equals(type)) {
     contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
     contentUri = null;//不获取视频
    } else if ("audio".equals(type)) {
     contentUri = null;//不获取音频
    }
    String selection = MediaStore.Images.Media._ID + "=?";
    String[] selectionArgs = new String[]{split[1]};
    return getDataColumn(context, contentUri, selection, selectionArgs);
   }
  } // MediaStore (and general)
  else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
   if (isGooglePhotosUri(imageUri))
    return imageUri.getLastPathSegment();
   return getDataColumn(context, imageUri, null, null);
  }
  // File
  else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
   return imageUri.getPath();
  }
  return null;
 }

 public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
  Cursor cursor = null;
  String column = MediaStore.Images.Media.DATA;
  String[] projection = {column};
  try {
   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
   if (cursor != null && cursor.moveToFirst()) {
    int index = cursor.getColumnIndexOrThrow(column);
    return cursor.getString(index);
   }
  } finally {
   if (cursor != null)
    cursor.close();
  }
  return null;
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is ExternalStorageProvider.
  */
 public static boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is DownloadsProvider.
  */
 public static boolean isDownloadsDocument(Uri uri) {
  return "com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is MediaProvider.
  */
 public static boolean isMediaDocument(Uri uri) {
  return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is Google Photos.
  */
 public static boolean isGooglePhotosUri(Uri uri) {
  return "com.google.android.apps.photos.content".equals(uri.getAuthority());
 }

 /**
  * 创建图片缩略图
  *
  * @param filePath
  * @return
  */
 public static Bitmap createImageThumbnail(String filePath) {
  Bitmap bitmap = null;
  BitmapFactory.Options opts = new BitmapFactory.Options();
  opts.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(filePath, opts);
  opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);
  opts.inJustDecodeBounds = false;
  try {
   bitmap = BitmapFactory.decodeFile(filePath, opts);
  } catch (Exception e) {
   // TODO: handle exception
  }
  return bitmap;
 }

 public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
  int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
  int roundedSize;
  if (initialSize 

因为 Android4.4以上版本获得的图片URI是com.xxxxx的,因此需要在工具类里做判断,否则得不到图片的绝对地址。

工具类参考了别人的一篇博客,忘了留博客地址了,请原博主谅解。

最后需要加上一个权限:

读完爱站技术频道介绍的安卓开发之QQ图片的选择效果,相信肯定对你有帮助,最后提醒小伙伴,学习不能一蹴而就,一定要坚持不懈哦。

上一篇:教你简单使用oksocket和Android

下一篇:Android为任何视图添加全屏倾斜水印

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载