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

自訂 Toast 顯示圖片:打造圖片上傳預覽提示

編輯:關於 Android 程式設計

在 Android 開發中,Toast 並非只能顯示一行單調的文字。透過自訂版面配置,我們完全可以把上傳後的圖片直接呈現在提示框裡,讓使用者即時看到預覽效果。本文就來拆解如何自訂 Toast 版面,完成一個圖片上傳的視覺提示。

先來看看最終的呈現效果:

一、整體思路

核心流程可以拆成幾個環節:使用者點擊圖片上傳入口,透過對話框選擇「拍照」或「相簿」,取得圖片後進行裁剪與壓縮,最後把處理好的 Bitmap 塞進自訂的 Toast 版面中顯示。整個 Activity 主要負責協調拍照、選圖、裁剪與展示這幾個步驟。

二、Activity 主要邏輯

下方是一個以 GridView 為入口的 Activity,透過不同 item 觸發拍照上傳、掃碼、撥號、地圖定位、搖一搖、語音輸入、錄影、通訊錄等多項手機 API。其中圖片上傳的部分由 selectPhoto() 負責。

package com.lvche.lvchedingdang.activity.api_calling;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
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.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

/** 手機 API 調用 */
public class APICallingActivity extends BaseActivity implements PhotoShop {

    private MyGridView gridview;
    private final static int SCANNIN_GREQUEST_CODE = 1;
    /** 使用相機拍照獲取圖片 */
    protected static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    /** 使用相簿中的圖片 */
    protected static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    private Uri photoUri;
    private String picPath;
    private boolean isCutPic;
    private String PHONE_NUM = "13800138000";
    /** 地圖定位 */
    private static final int REQUEST_CODE_MAP = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_api_calling);
        initGridView();
    }

    /** 上傳時,選擇獲取圖片的方式 */
    public void selectPhoto() {
        String datas[] = { "拍照獲取照片", "從相簿中選擇照片" };
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("選擇圖片")
                .setItems(datas, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        if (item == 0) {
                            takePhoto();   // 拍照
                        } else {
                            pickPhoto();   // 相簿
                        }
                        dialog.dismiss();
                    }
                });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /** 拍照獲取圖片 */
    public void takePhoto() {
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues values = new ContentValues();
            photoUri = getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
        } else {
            MyToast.show(getApplicationContext(), "內存卡不存在", Toast.LENGTH_SHORT);
        }
    }

    /** 從相簿中取圖片 */
    public void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }
}

這裡有個實務上的小細節:拍照時若不透過 ContentValues 事先登記照片路徑,取回的往往只是縮圖,畫質會明顯變差。先插入一筆記錄取得 photoUri,再把它塞給相機,就能拿到原始尺寸的照片。

三、Toast 操作的核心片段

真正讓圖片出現在提示框裡的,是下面這段 showImage()。它透過 LayoutInflater 把自訂的 XML 版面轉成 View,找到其中的 ImageView,設定 Bitmap 並依原圖比例縮放,最後掛到 Toast 上顯示。

public void showImage(Bitmap bitmap) {
    if (bitmap == null) {
        MyToast.show(getApplicationContext(), "圖片似乎不正確~!!", Toast.LENGTH_SHORT);
        return;
    }
    LayoutInflater inflater = getLayoutInflater();
    // 將布局文件轉換成相應的 View 對象
    View layout = inflater.inflate(R.layout.toast_upload_img,
            (ViewGroup) findViewById(R.id.toast_layout_root));
    // 從 layout 中按照 id 查找 imageView 對象
    ImageView imageView = (ImageView) layout.findViewById(R.id.upload_img);
    // 設置 ImageView 的圖片
    imageView.setImageBitmap(bitmap);
    int scaleHeight = bitmap.getHeight() * 200 / bitmap.getWidth();
    imageView.setLayoutParams(new LinearLayout.LayoutParams(200, scaleHeight));
    // 實例化一個 Toast 對象
    Toast toast = new Toast(getApplicationContext());
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setView(layout);
    toast.show();
}

四、自訂 Toast 版面配置

版面本身很簡單,一個 LinearLayout 裡放一個帶邊框背景的 ImageView 即可:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/upload_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toast_custom_border"
        android:scaleType="fitXY"
        android:src="@drawable/icon_nav_icons" />

</LinearLayout>

五、邊框背景 drawable

為了讓圖片看起來有個清楚的邊界,可以用一個 shape 定義白底加上灰色描邊:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff" />
    <stroke
        android:width="1dp"
        android:color="#AAA5A5" />
    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />
</shape>

這樣一來,使用者上傳圖片後就能直接在 Toast 中看到縮圖預覽,互動回饋比單純的文字提示友善許多。

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