編輯:關於 Android 程式設計
本文以 MultiImageSelector 為基礎,示範如何在 Android 中做出接近微信體驗的多選圖片與拍照流程。整個實作可以拆成七個環節。
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);
}
選擇模式、最大選擇數量、是否啟用相機等,都透過它設定,不必自己刻一套相簿邏輯。
一個 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>
getSupportFragmentManager().beginTransaction()
.add(R.id.image_grid, Fragment.instantiate(this,
MultiImageSelectorFragment.class.getName(), bundle))
.commit();
<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 的互動設計。
Android SQLite 入門:DbHelper、CRUD 與 Spinner 資料綁定
SQLite 是 Android 內建的輕量級關聯式資料庫,適合儲存本地結構化資料。開發時通常會建立 SQLiteOpenHelper,負責建立與升級資料表。 建立資料
自製安全鍵盤:用 KeyboardView 打造字母、數字、符號三合一輸入盤
一直知道 Android 有 KeyboardView 這個元件可以做自訂鍵盤,只是過去沒派上用場。某天看到某銀行 App 的密碼輸入鍵盤,配色與排版都很講究,於是決定動
Android 雷達圖(蜘蛛網圖)自定義 View 繪製教學
簡介 前陣子因為專案需求,要做一張雷達圖來呈現使用者的各項成就值。這個圖表的繪製邏輯其實不難,只要思路清楚、按部就班地畫就好。其中用得最多的是 Path 類別——有了它,
為自訂 View 加上 XML 屬性:三個步驟完整說明
前面已經寫過幾篇關於自訂 View 的文章,這裡就不再從頭談起,有興趣的讀者可以回頭看看之前的內容。先前的文章主要在說明「如何使用自訂 View」以及「為什麼要用自訂 V