การเลือกรูปภาพจากคลังได้หลายๆ รูป ทำยังไงไปดูกันเลย (Android)
การเลือกรูปจากคลังภาพ |
สวัสดีครับห่างหายไปนานกับการเขียนบทความ วันนี้ผมอยากจะมาแชร์ตัวอย่างการทำเลือกรูปจากคลังภาพแบบหลายๆ รูปมาใช้งาน ซึ่งปกติเราอาจจะคุ้นชินกับการเลือกมาแค่ 1 รูป ดังนั้นตัวอย่างนี้จึงพิเศษกว่าครับ สามารถทำได้จริง
ตัวอย่างนี้ไม่ต้อง Import Dependencie อะไรทั้งนั้น
การออกแบบ
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <HorizontalScrollView android:id="@+id/scroll1" android:layout_width="match_parent" android:layout_height="wrap_content" tools:ignore="MissingConstraints"> <LinearLayout android:id="@+id/lnrImages" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </LinearLayout> </HorizontalScrollView> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" tools:ignore="MissingConstraints"> <Button android:id="@+id/btnAddPhots" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Add Photo" /> <Button android:id="@+id/btnSaveImages" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Save" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
custom_gallery.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:gravity="center" android:orientation="vertical"> <GridView android:id="@+id/grdImages" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:columnWidth="90dp" android:gravity="center" android:horizontalSpacing="10dp" android:numColumns="3" android:stretchMode="columnWidth" android:verticalSpacing="10dp" /> <Button android:id="@+id/btnSelect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="Select" /> </LinearLayout>
ไฟล์นี้จะเป็นการกำหนดแถวของรูปภาพในรูปแบบ Grid
custom_gallery_item.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imgThumb" android:layout_width="match_parent" android:layout_height="match_parent"/> <CheckBox android:id="@+id/chkImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top|right"/> </FrameLayout>
ต่อมาจะเป็นในส่วนของโค้ดการทำงานนะครับ (java)
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | package com.test.select; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private LinearLayout lnrImages; private Button btnAddPhots; private Button btnSaveImages; private ArrayList<String> imagesPathList; private Bitmap yourbitmap; private Bitmap resized; private final int PICK_IMAGE_MULTIPLE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000); lnrImages = (LinearLayout) findViewById(R.id.lnrImages); btnAddPhots = (Button) findViewById(R.id.btnAddPhots); btnSaveImages = (Button) findViewById(R.id.btnSaveImages); btnAddPhots.setOnClickListener(this); btnSaveImages.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btnAddPhots: Intent intent = new Intent(MainActivity.this, CustomPhotoGalleryActivity.class); startActivityForResult(intent, PICK_IMAGE_MULTIPLE); break; case R.id.btnSaveImages: if (imagesPathList != null) { if (imagesPathList.size() > 1) { Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, imagesPathList.size() + " no of image are selected", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, " no images are selected", Toast.LENGTH_SHORT).show(); } break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if(requestCode == PICK_IMAGE_MULTIPLE){ imagesPathList = new ArrayList<String>(); String[] imagesPath = data.getStringExtra("data").split("\\|"); try{ lnrImages.removeAllViews(); }catch (Throwable e){ e.printStackTrace(); } for (int i=0;i<imagesPath.length;i++){ imagesPathList.add(imagesPath[i]); yourbitmap = BitmapFactory.decodeFile(imagesPath[i]); ImageView imageView = new ImageView(this); imageView.setImageBitmap(yourbitmap); imageView.setAdjustViewBounds(true); lnrImages.addView(imageView); } } } } } |
CustomPhotoGalleryActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | package com.test.select; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class CustomPhotoGalleryActivity extends AppCompatActivity { private GridView grdImages; private Button btnSelect; private ImageAdapter imageAdapter; private String[] arrPath; private boolean[] thumbnailsselection; private int ids[]; private int count; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_gallery); grdImages= (GridView) findViewById(R.id.grdImages); btnSelect= (Button) findViewById(R.id.btnSelect); final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; final String orderBy = MediaStore.Images.Media._ID; @SuppressWarnings("deprecation") Cursor imagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy); int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID); this.count = imagecursor.getCount(); this.arrPath = new String[this.count]; ids = new int[count]; this.thumbnailsselection = new boolean[this.count]; for (int i = 0; i < this.count; i++) { imagecursor.moveToPosition(i); ids[i] = imagecursor.getInt(image_column_index); int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA); arrPath[i] = imagecursor.getString(dataColumnIndex); } imageAdapter = new ImageAdapter(); grdImages.setAdapter(imageAdapter); imagecursor.close(); btnSelect.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final int len = thumbnailsselection.length; int cnt = 0; String selectImages = ""; for (int i = 0; i < len; i++) { if (thumbnailsselection[i]) { cnt++; selectImages = selectImages + arrPath[i] + "|"; } } if (cnt == 0) { Toast.makeText(getApplicationContext(), "Please select at least one image", Toast.LENGTH_LONG).show(); } else { Log.d("SelectedImages", selectImages); Intent i = new Intent(); i.putExtra("data", selectImages); setResult(Activity.RESULT_OK, i); finish(); } } }); } @Override public void onBackPressed() { setResult(Activity.RESULT_CANCELED); super.onBackPressed(); } private void setBitmap(final ImageView iv, final int id) { new AsyncTask<Void, Void, Bitmap>() { @Override protected Bitmap doInBackground(Void... params) { return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null); } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); iv.setImageBitmap(result); } }.execute(); } public class ImageAdapter extends BaseAdapter { private LayoutInflater mInflater; public ImageAdapter() { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return count; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.custom_gallery_item, null); holder.imgThumb = (ImageView) convertView.findViewById(R.id.imgThumb); holder.chkImage = (CheckBox) convertView.findViewById(R.id.chkImage); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.chkImage.setId(position); holder.imgThumb.setId(position); holder.chkImage.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox) v; int id = cb.getId(); if (thumbnailsselection[id]) { cb.setChecked(false); thumbnailsselection[id] = false; } else { cb.setChecked(true); thumbnailsselection[id] = true; } } }); holder.imgThumb.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int id = holder.chkImage.getId(); if (thumbnailsselection[id]) { holder.chkImage.setChecked(false); thumbnailsselection[id] = false; } else { holder.chkImage.setChecked(true); thumbnailsselection[id] = true; } } }); try { setBitmap(holder.imgThumb, ids[position]); } catch (Throwable e) { } holder.chkImage.setChecked(thumbnailsselection[position]); holder.id = position; return convertView; } } /** * Inner class * @author tasol */ class ViewHolder { ImageView imgThumb; CheckBox chkImage; int id; } } |
Soruce Code : https://github.com/tanat29/SelectMultipleImage
ความคิดเห็น