
本文实例为大家分享了AndroID实现QQ图片说说照片选择的具体代码,供大家参考,具体内容如下
效果展示
布局文件布局是很简单的,一个GrIDVIEw,直接上布局:
layout/activity_add_photo.xml
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical"> <relativeLayout androID:layout_wIDth="match_parent" androID:layout_height="60dp" androID:background="#00BB9C"> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_centerInParent="true" androID:text="写动态" androID:textAppearance="?androID:attr/textAppearanceLarge" androID:textcolor="@androID:color/white" /> <TextVIEw androID:ID="@+ID/send" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_alignParentRight="true" androID:layout_centerVertical="true" androID:layout_marginRight="10dp" androID:text="发送" androID:textAppearance="?androID:attr/textAppearanceLarge" androID:textcolor="@androID:color/white" /> </relativeLayout> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:layout_margin="16dp" androID:orIEntation="vertical"> <EditText androID:layout_wIDth="match_parent" androID:layout_height="100dp" androID:enabled="false" androID:focusable="false" androID:gravity="top" androID:hint="分享您的那点新鲜事儿..." androID:maxlines="5" /> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:padding="5dp"> <GrIDVIEw androID:ID="@+ID/grIDvIEw" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:numColumns="4" /> </linearLayout> </linearLayout></linearLayout>
layout/activity_add_photo_gv_items.xml 使用了自定义的vIEw使得布局为正方形
<?xml version="1.0" enCoding="utf-8"?><com.shenhua.tabhostdemo.selectimg.SquarerelativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content"> <ImageVIEw androID:ID="@+ID/main_grIDVIEw_item_photo" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:layout_centerInParent="true" androID:contentDescription="@null" androID:padding="5dp" androID:scaleType="fitXY" /> <CheckBox androID:ID="@+ID/main_grIDVIEw_item_cb" androID:layout_wIDth="20dp" androID:layout_height="20dp" androID:layout_alignParentEnd="true" androID:layout_alignParentRight="true" androID:layout_alignParenttop="true" androID:layout_margin="2dp" androID:background="@drawable/ic_delete" androID:backgroundTint="#00BB9C" androID:button="@null" /></com.shenhua.tabhostdemo.selectimg.SquarerelativeLayout>
代码实现
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<String> 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.size() - 1; i++) { bitmap = BitmapFactory.decodefile(List.get(i)); bmpCompressed = Bitmap.createScaledBitmap(bitmap,640,480,true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bmpCompressed.compress(Bitmap.CompressFormat.JPEG,100,bos); byte[] data = bos.toByteArray(); System.out.println(data); } } private voID initData() { if (List == null) { List = new ArrayList<>(); 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() < img_COUNT) { Intent i = new Intent(Intent.ACTION_PICK,androID.provIDer.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i,0); } else Toast.makeText(UploadPhotoActivity.this,"最多只能选择7张照片!",Toast.LENGTH_SHORT).show(); } } }); refreshAdapter(); } private voID refreshAdapter() { if (List == null) { List = new ArrayList<>(); } 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,selection,selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(imageUri.getScheme())) { if (isGooglePhotosUri(imageUri)) return imageUri.getLastPathSegment(); return getDataColumn(context,imageUri,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,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 <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private static int computeInitialSampleSize(BitmapFactory.Options options,int maxnumOfPixels) { double w = options.outWIDth; double h = options.outHeight; int lowerBound = (maxnumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxnumOfPixels)); int upperBound = (minSIDeLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSIDeLength),Math.floor(h / minSIDeLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapPing zone. return lowerBound; } if ((maxnumOfPixels == -1) && (minSIDeLength == -1)) { return 1; } else if (minSIDeLength == -1) { return lowerBound; } else { return upperBound; } }}因为 AndroID4.4以上版本获得的图片URI是com.xxxxx的,因此需要在工具类里做判断,否则得不到图片的绝对地址。
工具类参考了别人的一篇博客,忘了留博客地址了,请原博主谅解。
最后需要加上一个权限:
<uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE" />
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的Android实现QQ图片说说照片选择效果全部内容,希望文章能够帮你解决Android实现QQ图片说说照片选择效果所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)