亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android實現QQ圖片說說照片選擇效果

發布時間:2020-08-27 03:50:16 來源:腳本之家 閱讀:170 作者:神話2009 欄目:移動開發

本文實例為大家分享了Android實現QQ圖片說說照片選擇的具體代碼,供大家參考,具體內容如下

效果展示

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, 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 <= 8) {
   roundedSize = 1;
   while (roundedSize < initialSize) {
    roundedSize <<= 1;
   }
  } else {
   roundedSize = (initialSize + 7) / 8 * 8;
  }
  return roundedSize;
 }

 private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, 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" />

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

成安县| 阳山县| 图片| 宁安市| 佛学| 咸宁市| 新竹县| 新泰市| 循化| 长宁县| 迁西县| 广宁县| 剑阁县| 南郑县| 天镇县| 赣榆县| 鹤山市| 丹巴县| 翁源县| 潮安县| 平度市| 富锦市| 微博| 巫山县| 丰都县| 连江县| 梨树县| 静宁县| 资兴市| 东宁县| 乌鲁木齐市| 花莲市| 余干县| 呼图壁县| 乐陵市| 中西区| 绥滨县| 新郑市| 吐鲁番市| 都昌县| 潮州市|