您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Android中怎么利用GridView實現微信圖片上傳功能,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
項目結構:
下面直接上代碼。
整體的布局文件activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/index" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="44dp" android:background="#24cf5f" android:orientation="horizontal" > <ImageView android:id="@+id/back" android:layout_width="match_parent" android:layout_height="20dp" android:layout_gravity="center" android:layout_weight="5" android:src="@drawable/back" /> <TextView android:layout_width="fill_parent" android:layout_height="44dp" android:layout_weight="1" android:gravity="center" android:paddingRight="40dp" android:text="圖片上傳" android:textColor="#FFFFFF" android:textSize="30px" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:layout_weight="1" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="請選擇上傳的圖片" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="(友情提示:圖片最多可添加9張,點擊可刪除選擇的圖片)" android:textSize="18px" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" > <com.yihang.MyGridView.MyGridView android:id="@+id/gridView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:layout_weight="111" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="5dp" android:numColumns="4" android:stretchMode="columnWidth" android:verticalSpacing="5dp" /> </LinearLayout> </LinearLayout> </ScrollView> <Button android:id="@+id/bt_submit" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="bottom" android:layout_weight="5.2" android:background="#24cf5f" android:text="上傳" android:textColor="#FFFFFF" android:textSize="16sp" /> </LinearLayout>
activity:MainActivity
package com.yihang.activity; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.SimpleAdapter; import android.widget.SimpleAdapter.ViewBinder; import android.widget.Toast; import com.yihang.dialog.MyDialog; import com.yihang.dialog.MyDialog.OnButtonClickListener; import com.yihang.photodemo.R; public class MainActivity extends Activity implements OnButtonClickListener, OnItemClickListener{ private MyDialog dialog;// 圖片選擇對話框 public static final int NONE = 0; public static final int PHOTOHRAPH = 1;// 拍照 public static final int PHOTOZOOM = 2; // 縮放 public static final int PHOTORESOULT = 3;// 結果 public static final String IMAGE_UNSPECIFIED = "image/*"; private GridView gridView; // 網格顯示縮略圖 private final int IMAGE_OPEN = 4; // 打開圖片標記 private String pathImage; // 選擇圖片路徑 private Bitmap bmp; // 導入臨時圖片 private ArrayList<HashMap<String, Object>> imageItem; private SimpleAdapter simpleAdapter; // 適配器 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); /* * 防止鍵盤擋住輸入框 不希望遮擋設置activity屬性 android:windowSoftInputMode="adjustPan" * 希望動態調整高度 android:windowSoftInputMode="adjustResize" */ getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 鎖定屏幕 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); init(); initData(); } private void init() { gridView = (GridView) findViewById(R.id.gridView); gridView.setOnItemClickListener(this); dialog = new MyDialog(this); dialog.setOnButtonClickListener(this); // activity中調用其他activity中組件的方法 LayoutInflater layout = this.getLayoutInflater(); View view = layout.inflate(R.layout.layout_select_photo, null); } private void initData() { /* * 載入默認圖片添加圖片加號 */ bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic); // 加號 imageItem = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", bmp); imageItem.add(map); simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic, new String[] { "itemImage" }, new int[] { R.id.imageView1 }); simpleAdapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Object data, String textRepresentation) { // TODO Auto-generated method stub if (view instanceof ImageView && data instanceof Bitmap) { ImageView i = (ImageView) view; i.setImageBitmap((Bitmap) data); return true; } return false; } }); gridView.setAdapter(simpleAdapter); } @Override public void camera() { // TODO Auto-generated method stub Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File( Environment.getExternalStorageDirectory(), "temp.jpg"))); startActivityForResult(intent, PHOTOHRAPH); } @Override public void gallery() { // TODO Auto-generated method stub Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, IMAGE_OPEN); } @Override public void cancel() { // TODO Auto-generated method stub dialog.cancel(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == NONE) return; // 拍照 if (requestCode == PHOTOHRAPH) { // 設置文件保存路徑這里放在跟目錄下 File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); startPhotoZoom(Uri.fromFile(picture)); } if (data == null) return; // 處理結果 if (requestCode == PHOTORESOULT) { Bundle extras = data.getExtras(); if (extras != null) { Bitmap photo = extras.getParcelable("data"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)壓縮文件 // 將圖片放入gridview中 HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", photo); imageItem.add(map); simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic, new String[] { "itemImage" }, new int[] { R.id.imageView1 }); simpleAdapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Object data, String textRepresentation) { // TODO Auto-generated method stub if (view instanceof ImageView && data instanceof Bitmap) { ImageView i = (ImageView) view; i.setImageBitmap((Bitmap) data); return true; } return false; } }); gridView.setAdapter(simpleAdapter); simpleAdapter.notifyDataSetChanged(); dialog.dismiss(); } } // 打開圖片 if (resultCode == RESULT_OK && requestCode == IMAGE_OPEN) { startPhotoZoom(data.getData()); } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (!TextUtils.isEmpty(pathImage)) { Bitmap addbmp = BitmapFactory.decodeFile(pathImage); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", addbmp); imageItem.add(map); simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic, new String[] { "itemImage" }, new int[] { R.id.imageView1 }); simpleAdapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Object data, String textRepresentation) { // TODO Auto-generated method stub if (view instanceof ImageView && data instanceof Bitmap) { ImageView i = (ImageView) view; i.setImageBitmap((Bitmap) data); return true; } return false; } }); gridView.setAdapter(simpleAdapter); simpleAdapter.notifyDataSetChanged(); // 刷新后釋放防止手機休眠后自動添加 pathImage = null; dialog.dismiss(); } } @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // TODO Auto-generated method stub if (imageItem.size() == 10) { // 第一張為默認圖片 Toast.makeText(MainActivity.this, "圖片數9張已滿", Toast.LENGTH_SHORT).show(); } else if (position == 0) { // 點擊圖片位置為+ 0對應0張圖片 // 選擇圖片 dialog.show(); // 通過onResume()刷新數據 } else { dialog(position); } } /* * Dialog對話框提示用戶刪除操作 position為刪除圖片位置 */ protected void dialog(final int position) { AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setMessage("確認移除已添加圖片嗎?"); builder.setTitle("提示"); builder.setPositiveButton("確認", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); imageItem.remove(position); simpleAdapter.notifyDataSetChanged(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void startPhotoZoom(Uri uri) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, IMAGE_UNSPECIFIED); intent.putExtra("crop", "true"); // aspectX aspectY 是寬高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪圖片寬高 intent.putExtra("outputX", 64); intent.putExtra("outputY", 64); intent.putExtra("return-data", true); startActivityForResult(intent, PHOTORESOULT); } }
彈出的對話框(仿照微信來完成):MyDialog
package com.yihang.dialog; import com.yihang.photodemo.R; import android.app.Dialog; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; /** * 對話框實現類 * @author admin * */ public class MyDialog extends Dialog implements OnClickListener { public MyDialog(Context context) { super(context,R.style.myDialog); //初始化布局 setContentView(R.layout.layout_select_photo); Window dialogWindow = getWindow(); dialogWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); dialogWindow.setGravity(Gravity.BOTTOM); setCanceledOnTouchOutside(true); findViewById(R.id.btn_camera).setOnClickListener(this); findViewById(R.id.btn_gallery).setOnClickListener(this); findViewById(R.id.btn_cancel).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_camera: onButtonClickListener.camera(); break; case R.id.btn_gallery: onButtonClickListener.gallery(); break; case R.id.btn_cancel: onButtonClickListener.cancel(); break; default: break; } } /** * 按鈕的監聽器 * @author Orathee * @date 2014年3月20日 下午4:28:39 */ public interface OnButtonClickListener{ void camera(); void gallery(); void cancel(); } private OnButtonClickListener onButtonClickListener; public OnButtonClickListener getOnButtonClickListener() { return onButtonClickListener; } public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) { this.onButtonClickListener = onButtonClickListener; } }
對話框的布局文件:layout_select_photo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="@drawable/btn_style_alert_dialog_background" android:padding="20dp"> <TextView android:id="@+id/btn_camera" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" android:background="@drawable/btn_style_alert_dialog_button" android:textColor="#0f0f0f" android:text="拍照" android:shadowDx="0.5" android:shadowDy="0.5" android:shadowRadius="0.5" android:shadowColor="#ffffff" android:layout_marginBottom="10dp" android:padding="10dp" android:gravity="center"/> <TextView android:id="@+id/btn_gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="18sp" android:background="@drawable/btn_style_alert_dialog_button" android:textColor="#0f0f0f" android:text="從相冊中選擇" android:shadowDx="0.5" android:shadowDy="0.5" android:shadowRadius="0.5" android:shadowColor="#ffffff" android:layout_marginBottom="10dp" android:padding="10dp" android:gravity="center"/> <TextView android:id="@+id/btn_cancel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/btn_style_alert_dialog_cancel" android:textColor="#ffffff" android:textSize="18sp" android:text="取消" android:shadowDx="0.5" android:shadowDy="0.5" android:shadowRadius="0.5" android:shadowColor="#000000" android:layout_marginTop="10dp" android:padding="10dp" android:gravity="center"/> </LinearLayout> </LinearLayout>
自定義的GridView:
package com.yihang.MyGridView; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class MyGridView extends GridView { public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public MyGridView(Context context) { super(context); } public MyGridView(Context context, AttributeSet attrs, int defStyle) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
關于Android中怎么利用GridView實現微信圖片上傳功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。