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

仿微信的圖片選擇與拍照功能,Android 完整實作

編輯:關於 Android 程式設計

本文以 MultiImageSelector 為基礎,示範如何在 Android 中做出接近微信體驗的多選圖片與拍照流程。整個實作可以拆成七個環節。

一、先處理 6.0 的執行期權限

Android 6.0 之後,相機與讀取外部儲存都必須動態申請:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions((Activity) this, new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_STORAGE_READ_ACCESS_PERMISSION);
}

二、用 MultiImageSelector 管理行為

選擇模式、最大選擇數量、是否啟用相機等,都透過它設定,不必自己刻一套相簿邏輯。

三、選擇頁的版面配置

一個 Toolbar 加一個 FrameLayout 就足夠,FrameLayout 稍後用來掛載 Fragment:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="#181819"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/mis_actionbar_color"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:minHeight="?android:attr/actionBarSize">
        <Button
            android:id="@+id/commit"
            android:background="@drawable/mis_action_btn"
            android:layout_marginRight="16dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:textColor="@color/mis_default_text_color"
            android:textSize="14sp"
            android:layout_gravity="right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </android.support.v7.widget.Toolbar>
    <FrameLayout
        android:id="@+id/image_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

四、掛上 MultiImageSelectorFragment

getSupportFragmentManager().beginTransaction()
        .add(R.id.image_grid, Fragment.instantiate(this,
                MultiImageSelectorFragment.class.getName(), bundle))
        .commit();

五、Fragment 內用 GridView 呈現相簿

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:background="@android:color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <GridView
        android:id="@+id/grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="@dimen/mis_space_size"
        android:verticalSpacing="@dimen/mis_space_size"
        android:paddingBottom="?android:attr/actionBarSize"
        android:clipToPadding="false"
        android:numColumns="3"/>
    <RelativeLayout
        android:id="@+id/footer"
        android:background="#cc000000"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize">
        <Button
            android:id="@+id/category_btn"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerVertical="true"
            android:textColor="@color/mis_folder_text_color"
            tools:text="所有圖片"
            android:textSize="16sp"
            android:gravity="center_vertical"
            android:drawableRight="@drawable/mis_text_indicator"
            android:background="@null"
            android:singleLine="true"
            android:ellipsize="end"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
    </RelativeLayout>
</RelativeLayout>

六、非同步載入完成後餵資料

透過 LoaderManager 的 LoaderCallbacks 在背景掃描媒體庫,完成後再交給 adapter:

mImageAdapter.setData(images);

七、點擊行為與相機呼叫

GridView 的項目點擊要區分「第一格是相機入口」與「其餘是照片」兩種情況:

mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view,
                            int i, long l) {
        if (mImageAdapter.isShowCamera()) {
            if (i == 0) {
                showCameraAction();
            } else {
                Image image = (Image) adapterView.getAdapter().getItem(i);
                selectImageFromGrid(image, mode);
            }
        } else {
            Image image = (Image) adapterView.getAdapter().getItem(i);
            selectImageFromGrid(image, mode);
        }
    }
});

相機部分需要建立暫存檔案,並透過 EXTRA_OUTPUT 指定輸出路徑,拍完照再回來處理:

private void showCameraAction() {
    if (ContextCompat.checkSelfPermission(getContext(),
            Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                getString(R.string.mis_permission_rationale_write_storage),
                REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
    } else {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            try {
                mTmpFile = FileUtils.createTmpFile(getActivity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (mTmpFile != null && mTmpFile.exists()) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(mTmpFile));
                startActivityForResult(intent, REQUEST_CAMERA);
            } else {
                Toast.makeText(getActivity(),
                        R.string.mis_error_image_not_exist,
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), R.string.mis_msg_no_camera,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

選圖回調則要同時照顧單選與多選兩種模式,多選時還要檢查數量上限:

private void selectImageFromGrid(Image image, int mode) {
    if (image != null) {
        if (mode == MODE_MULTI) {
            if (resultList.contains(image.path)) {
                resultList.remove(image.path);
                if (mCallback != null) {
                    mCallback.onImageUnselected(image.path);
                }
            } else {
                if (selectImageCount() == resultList.size()) {
                    Toast.makeText(getActivity(),
                            R.string.mis_msg_amount_limit,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                resultList.add(image.path);
                if (mCallback != null) {
                    mCallback.onImageSelected(image.path);
                }
            }
            mImageAdapter.select(image);
        } else if (mode == MODE_SINGLE) {
            if (mCallback != null) {
                mCallback.onSingleImageSelected(image.path);
            }
        }
    }
}

七個環節串起來,一個堪用的圖片選擇器就完成了。相簿掃描、權限、拍照暫存、選擇上限這些瑣事,交给成熟套件能省下不少時間,把力氣留給真正屬於自己 App 的互動設計。

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