Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 相簿圖片瀏覽與多選:GridView 實作完整教學

編輯:關於 Android 程式設計

想做到的效果

這次要實作的是一個典型的「選取圖片」頁面:

1. 第一格固定是相機入口,點擊直接開啟系統相機拍照。

2. 其餘格子顯示裝置內所有已存的圖片,單擊進入大圖檢視,長按則讓每張圖右上方浮現 CheckBox,進入多選模式。

3. 選完按「完成」,把選取的檔案清單回傳給上一頁。

成品如下:

一、MainActivity

public class MainActivity extends AppCompatActivity
        implements AdapterView.OnItemClickListener,
                   AdapterView.OnItemLongClickListener,
                   ImageAdapter.OnImageCheckListener,
                   View.OnClickListener {

    private static final int CAMERA_CODE = 12;

    List<File> fileList = new ArrayList<>();
    ImageAdapter adapter;
    GridView gvImage;
    TextView tvFinish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // 彈出對話框並載入資料
        loadData();
    }

    private void initView() {
        gvImage = (GridView) findViewById(R.id.gv_image);
        tvFinish = (TextView) findViewById(R.id.tv_finish);
        adapter = new ImageAdapter(this, fileList);
        adapter.setOnImageCheckListener(this);
        gvImage.setAdapter(adapter);
        gvImage.setOnItemClickListener(this);
        gvImage.setOnItemLongClickListener(this);
        tvFinish.setOnClickListener(this);
    }

    private ProgressDialog showProgressDialog() {
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setTitle("提示");
        dialog.setMessage("正在加載圖片,請稍等。。。");
        dialog.show();
        return dialog;
    }

    private void loadData() {
        final ProgressDialog dialog = showProgressDialog();
        // 掃描檔案必須放在子執行緒,否則會卡住 UI
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 從 SD 卡根目錄開始遞迴
                getFile(Environment.getExternalStorageDirectory());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }.start();
    }

    public void getFile(File dir) {
        File[] files = dir.listFiles();
        if (files == null) return;
        for (File file : files) {
            if (file.isDirectory()) getFile(file);
            else {
                // 只收 png 與 jpg
                if (file.getName().endsWith(".png") || file.getName().endsWith(".jpg")) {
                    fileList.add(file);
                }
            }
        }
    }

    File cameraFile;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            // getAbsolutePath 回傳的路徑結尾沒有 "/",所以要自己補
            cameraFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/DCIM/" + System.currentTimeMillis() + ".png");
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // 指定輸出去向,拍照後照片才會落到我們的檔案
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
            startActivityForResult(intent, CAMERA_CODE);
        } else {
            // 其餘位置:打開大圖
            File file = fileList.get(position - 1);
            Intent intent = new Intent(this, ShowBigImage.class);
            intent.putExtra("file", file);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("TAG", resultCode + "---------------------");
        if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
            Log.e("TAG", (cameraFile.exists()) + "");
            // 新照片插到最前面
            fileList.add(0, cameraFile);
            adapter.notifyDataSetChanged();
        }
    }

    // 長按進入多選
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return false;
        else {
            adapter.open(position);
        }
        return true;
    }

    @Override
    public void onImageCheck(boolean b) {
        // b 代表 Adapter 中是否有勾選的項目
        tvFinish.setEnabled(b);
    }

    @Override
    public void onClick(View v) {
        // 收集被選中的資料
        // 這裡必須用 ArrayList,因为只有它實作了序列化,List 沒有
        ArrayList<File> resultList = new ArrayList<>();
        SparseBooleanArray booleanArray = adapter.getBooleanArray();
        for (int i = 0; i < booleanArray.size(); i++) {
            boolean isCheck = booleanArray.get(booleanArray.keyAt(i));
            if (isCheck) {
                int position = booleanArray.keyAt(i);
                resultList.add(fileList.get(position - 1));
            }
        }
        Intent intent = new Intent();
        intent.putExtra("list", resultList);
        setResult(RESULT_OK, intent);
        finish();
    }
}

二、ImageAdapter

這個 Adapter 肩負三件事:多一格相機入口、管理勾選狀態、以及透過回呼通知外層「是否還有勾選項」。

public class ImageAdapter extends ListItemAdapter<File> {

    private boolean select = false;
    private SparseBooleanArray booleanArray = new SparseBooleanArray();
    private OnImageCheckListener onImageCheckListener;

    public ImageAdapter(Context context, List<File> list) {
        super(context, list);
    }

    /** 進入多選模式 */
    public void open(int posisiont) {
        select = true;
        booleanArray.put(posisiont, true);
        if (onImageCheckListener != null) onImageCheckListener.onImageCheck(true);
        this.notifyDataSetChanged();
    }

    /** 退出多選模式 */
    public void close() {
        select = false;
        booleanArray.clear();
        notifyDataSetChanged();
    }

    public SparseBooleanArray getBooleanArray() {
        return booleanArray;
    }

    @Override
    public int getCount() {
        // 多出來的一格就是相機
        return super.getCount() + 1;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(mContext, R.layout.item_image, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (position == 0) {
            holder.image.setImageResource(R.mipmap.camera);
            holder.checkBox.setVisibility(View.GONE);
        } else {
            holder.image.setImageURI(Uri.fromFile(getItem(position - 1)));

            if (select) {
                holder.checkBox.setVisibility(View.VISIBLE);
                Boolean b = booleanArray.get(position);
                if (b == null || b == false) {
                    holder.checkBox.setChecked(false);
                } else {
                    holder.checkBox.setChecked(true);
                }

                // 注意:這裡刻意用 setOnClickListener 而不是 setOnCheckedChangeListener,
                // 因為 getView 會被反覆複用,setOnCheckedChangeListener 容易被上一輪的狀態誤觸
                holder.checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Boolean b = booleanArray.get(position);
                        if (b == null || b == false) b = true;
                        else b = false;
                        booleanArray.put(position, b);

                        // 掃過所有 boolean,只要還有一個 true 就保持啟用
                        for (int i = 0; i < booleanArray.size(); i++) {
                            boolean isChecked = booleanArray.get(booleanArray.keyAt(i));
                            if (isChecked) {
                                if (onImageCheckListener != null) onImageCheckListener.onImageCheck(true);
                                return;
                            }
                        }
                        // 一個都沒勾了,關閉完成鈕並退出多選
                        if (onImageCheckListener != null) onImageCheckListener.onImageCheck(false);
                        close();
                    }
                });
            } else {
                holder.checkBox.setVisibility(View.GONE);
            }
        }
        return convertView;
    }

    /** 回呼介面:寫在需要被通知的地方,由需要接收的一方實作 */
    public interface OnImageCheckListener {
        void onImageCheck(boolean b);
    }

    public void setOnImageCheckListener(OnImageCheckListener onImageCheckListener) {
        this.onImageCheckListener = onImageCheckListener;
    }

    class ViewHolder {
        ImageView image;
        CheckBox checkBox;

        public ViewHolder(View convertView) {
            image = (ImageView) convertView.findViewById(R.id.iv_image);
            int width = mContext.getResources().getDisplayMetrics().widthPixels / 3 - 2;
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, width);
            image.setLayoutParams(params);
            checkBox = (CheckBox) convertView.findViewById(R.id.cb_check);
        }
    }
}

三、ListItemAdapter 泛型基底類

/**
 * 在類別後面定義泛型,讓子類決定實際型別
 * (例如 List<File> 或 List<String>)
 */
public abstract class ListItemAdapter<T> extends BaseAdapter {

    protected Context mContext;
    protected List<T> mList;

    public ListItemAdapter(Context context, List<T> list) {
        mContext = context;
        mList = list;
    }

    /** 更換資料來源 */
    public void setList(List<T> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public T getItem(int position) {
        return mList.get(position);
    }

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

四、ShowBigImage 大圖檢視

public class ShowBigImage extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageView iv = new ImageView(this);
        File file = (File) getIntent().getSerializableExtra("file");
        iv.setImageURI(Uri.fromFile(file));
        setContentView(iv);
    }
}

五、布局檔

main_xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.imageselector.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="選取圖片"
            android:textColor="@android:color/white"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv_finish"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:enabled="false"
            android:text="完成"
            android:textColor="@color/textenable" />
    </RelativeLayout>

    <GridView
        android:id="@+id/gv_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="2dp"
        android:numColumns="3"
        android:verticalSpacing="2dp" />

</LinearLayout>

item_image.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#03030a">

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/camera" />

    <CheckBox
        android:id="@+id/cb_check"
        android:button="@null"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="@drawable/cb_selector"
        android:layout_alignParentRight="true"
        android:layout_margin="10dp" />

</RelativeLayout>

res/color/textenable.xml(讓「完成」按鈕依 enabled 狀態換色):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:color="@android:color/white" android:state_enabled="true" />
    <item android:color="@android:color/darker_gray" android:state_enabled="false" />
</selector>

六、幾個踩過才知道的坑

Android 7.0 之後,Uri.fromFile() 對外分享會觸發 FileUriExposedException,相機拍照存檔與大圖檢視都應改用 FileProvider 取得 content:// URI,並在 manifest 中宣告 provider 與 android:grantUriPermissions。

Android 6.0 之後,讀取外部儲存空間屬於危險權限,必須在執行期動態向使用者申請 READ_EXTERNAL_STORAGE,否則 listFiles() 會回傳空值。

這兩點是這份 2016 年的寫法在今日專案中必須補上的環節,其餘的 Adapter 複用與回呼設計則完全不受影響。

感謝閱讀,希望對你的實作有幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved