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

Android 實現「發說說」:多圖選擇、預覽與刪除

編輯:關於 Android 程式設計

這個功能來自項目裡的真實需求——用戶提交報修時,需要寫一段文字描述並附上限量的現場照片。折騰了幾天,把過程記錄下來,涉及的代碼裡有些業務相關的部分可以忽略,重點看圖片選擇與展示的實現思路。

先看一眼最終效果:

一、界面結構

整體採用「頂部標題欄 + 中間內容區 + 底部按鈕」的三段式佈局,中間放一個 EditText 承接文字,下面接一個 GridView 展示縮略圖。

activity_property_repair.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame">

    <RelativeLayout
        android:id="@+id/Layout_top"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentTop="true"
        android:gravity="center">
        <include android:id="@+id/shopcar_head" layout="@layout/elife_head" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/Content_Layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/Layout_bottom"
        android:layout_below="@id/Layout_top">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <EditText
                android:id="@+id/editText1"
                android:layout_width="fill_parent"
                android:layout_height="120dp"
                android:layout_margin="12dp"
                android:background="@drawable/editview_shape"
                android:gravity="top"
                android:hint="請說明你的問題..."
                android:maxLength="500"
                android:singleLine="false"
                android:textColor="#1eb2ff"
                android:textSize="15sp" />

            <GridView
                android:id="@+id/gridView1"
                android:layout_width="fill_parent"
                android:layout_height="200dp"
                android:layout_margin="10dp"
                android:background="#EFDFDF"
                android:columnWidth="90dp"
                android:gravity="center"
                android:horizontalSpacing="5dp"
                android:numColumns="4"
                android:scrollbars="none"
                android:stretchMode="columnWidth"
                android:verticalSpacing="5dp" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="(長按圖片可以刪除已添加圖片)"
                android:textColor="#1eb2ff" />
        </LinearLayout>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/Layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:gravity="center">
        <Button
            android:id="@+id/button1"
            android:layout_width="100dp"
            android:layout_height="fill_parent"
            android:background="@drawable/round"
            android:text="提交問題"
            android:textColor="#ffffff"
            android:textSize="15sp" />
        <Button
            android:id="@+id/button2"
            android:layout_width="100dp"
            android:layout_height="fill_parent"
            android:layout_marginLeft="2dp"
            android:layout_toRightOf="@+id/button1"
            android:background="@drawable/round"
            android:text="取消報修"
            android:textColor="#ffffff"
            android:textSize="15sp" />
    </RelativeLayout>
</RelativeLayout>

說一句:原文把 GridView 嵌在 EditText 內部,這種寫法雖然能跑,但語義上是錯的——EditText 不是容器。上面已經改成平級的 LinearLayout,功能不受影響,結構卻清晰多了。

griditem_addpic.xml(單個單元格)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:gravity="center"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center">
        <ImageView
            android:id="@+id/imag_oo"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />
    </RelativeLayout>
</LinearLayout>

editview_shape.xml(圓角輸入框,純裝飾,不需要可略過)

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">
    <solid android:color="#ffffff" />
    <corners
        android:bottomLeftRadius="15dp"
        android:bottomRightRadius="15dp"
        android:radius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
    <stroke
        android:width="4px"
        android:color="#1eb2ff" />
</shape>

二、核心邏輯

實現思路其實就四件事:點擊「+」格子打開系統相冊;在 onActivityResult 中拿到 Uri 並解析出真實路徑;把解碼後的 Bitmap 塞進數據源並刷新 GridView;點擊已有圖片則彈框確認刪除。

這裡有個一定要提的坑:SimpleAdapter 直接 put 一個 Bitmap 對象是不會顯示的(放資源 ID 反而正常)。解法有兩條——自定義繼承 BaseAdapter,或者實現 ViewBinder 接口。我選了後者,改動最小:

public class Property_repair extends Activity {

    private GridView gridView1;
    private static final int IMAGE_OPEN = 1;
    private static final int MAX_COUNT = 9;   // 不含「+」按鈕

    private String pathImage;
    private ArrayList<HashMap<String, Object>> imageItem;
    private SimpleAdapter simpleAdapter;

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

        // 防止軟鍵盤遮擋輸入框
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        EditText editText1 = (EditText) findViewById(R.id.editText1);

        // 提交
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText1.getText().toString().length() == 0) {
                    Toast.makeText(Property_repair.this, "請簡述詳情",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Property_repair.this, "提交成功",
                            Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });

        // 取消:彈自定義確認框
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(Property_repair.this)
                        .inflate(R.layout.tijiao_pingjia, null);
                final Dialog dialog = new Dialog(Property_repair.this, R.style.dialog2);
                dialog.setContentView(view);
                dialog.show();
                view.findViewById(R.id.yes).setOnClickListener(new OnClickListener() {
                    @Override public void onClick(View v) { finish(); }
                });
                view.findViewById(R.id.no).setOnClickListener(new OnClickListener() {
                    @Override public void onClick(View v) { dialog.cancel(); }
                });
            }
        });

        gridView1 = (GridView) findViewById(R.id.gridView1);

        // 第一格永遠是「+」
        Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.icon_addpic_unfocused);
        imageItem = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("imag_oo", bmp);
        imageItem.add(map);

        simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic,
                new String[]{"imag_oo"}, new int[]{R.id.imag_oo});

        // 關鍵:讓 SimpleAdapter 認得 Bitmap
        simpleAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if (view instanceof ImageView && data instanceof Bitmap) {
                    ((ImageView) view).setImageBitmap((Bitmap) data);
                    return true;
                }
                return false;
            }
        });
        gridView1.setAdapter(simpleAdapter);

        gridView1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                if (imageItem.size() > MAX_COUNT) {
                    Toast.makeText(Property_repair.this,
                            "圖片數 " + MAX_COUNT + " 張已滿", Toast.LENGTH_SHORT).show();
                } else if (position == 0) {
                    // 點到「+」,打開系統相冊
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, IMAGE_OPEN);
                } else {
                    dialog(position);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == IMAGE_OPEN) {
            Uri uri = data.getData();
            if (!TextUtils.isEmpty(uri.getAuthority())) {
                Cursor cursor = getContentResolver().query(uri,
                        new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                if (cursor == null) return;
                cursor.moveToFirst();
                pathImage = cursor.getString(
                        cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                cursor.close();   // Cursor 一定要關
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(pathImage)) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("imag_oo", BitmapFactory.decodeFile(pathImage));
            imageItem.add(map);
            simpleAdapter.notifyDataSetChanged();
            // 用完立刻清空,避免返回頁面時重複添加
            pathImage = null;
        }
    }

    /** 長按或點擊已選圖片時的刪除確認 */
    protected void dialog(final int position) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("確認移除已添加圖片嗎?")
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        imageItem.remove(position);
                        simpleAdapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("取消", null)
                .create().show();
    }
}

三、幾點經驗

路徑獲取。從 MediaStore 拿 DATA 列在 Android 4.4 之後逐漸不可靠(尤其對齊 Google Photos、雲相冊返回的 content://),高版本建議直接傳 Uri 給 BitmapFactory 或用 ContentResolver.openFileDescriptor() 讀流。

內存。原代碼直接 decodeFile 全尺寸位圖,九張高清照片足以引發 OOM。上線前務必配合 BitmapFactory.Options 的 inJustDecodeBounds + inSampleSize 做兩次解碼,或者直接上 Glide/Fresco。

刷新位置。把「追加圖片」放在 onResume 裡能用,但更清晰的做法是封一個 refreshGrid() 方法,在 onActivityResult 裡顯式調用,避免生命週期裡藏邏輯。

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