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

Android 動態添加圖片並自動換行

編輯:關於 Android 程式設計

專案裡需要一個「動態加入圖片、滿一行自動換行」的效果。一開始想用 GridView,但沒成功(具體原因已經忘了)。後來改用最直觀的做法:手動巢狀 LinearLayout,記錄下來備忘。

布局:一個空容器

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/sel_pic_6" />

    <LinearLayout
        android:id="@+id/linearlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    </LinearLayout>
</LinearLayout>

關鍵是外層那個空的 LinearLayout,orientation 為 vertical。每一「行」會是它的一個子 LinearLayout(orientation 為 horizontal),圖片則掛在這些行裡面。

Activity 實作

package org.cn.ruimit.pic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.cn.ruimit.R;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import com.china.hunbohui.BaseActivity;
import com.china.hunbohui.IApplication;

public class AddPicAty extends BaseActivity {

    private static final int SEL_PIC = 1;
    private LinearLayout linearLayout = null;
    private ArrayList<ImageBean> imageBeans;

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

    private void initView() {
        imageBeans = new ArrayList<ImageBean>();
        linearLayout = (LinearLayout) findViewById(R.id.linearlayout);

        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 開啟本地相冊
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, SEL_PIC);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SEL_PIC) {
                Uri uri = data.getData();
                String[] proj = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                // 取得所選圖片的欄位索引
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                // 將游標移至開頭,這一步很重要,漏了容易越界
                cursor.moveToFirst();
                String path = cursor.getString(column_index);

                ImageBean bean = new ImageBean();
                bean.setPath(path);
                imageBeans.add(bean);
                updateLayout();
            }
        }
    }

    /** 更新圖片布局 */
    private void updateLayout() {
        LinearLayout ll_horizontal = null;
        linearLayout.removeAllViews();

        for (int i = 0; i < imageBeans.size(); i++) {
            if (i % 4 == 0) {
                ll_horizontal = new LinearLayout(context);
                ll_horizontal.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.addView(ll_horizontal);
            }
            ImageView img = new ImageView(context);
            setImgLayoutParams(img);
            setImageBitmap(img, imageBeans.get(i).getPath());
            ll_horizontal.addView(img);
        }
    }

    /** 設定 ImageView 的尺寸 */
    private void setImgLayoutParams(ImageView img) {
        LayoutParams lp = new LayoutParams(0, 0);
        lp.width = (int) ((IApplication.with - 20 * IApplication.dencity
                          - 3 * 5 * IApplication.dencity) / 4);
        lp.height = lp.width;
        lp.rightMargin = (int) (5 * IApplication.dencity);
        lp.bottomMargin = (int) (5 * IApplication.dencity);
        img.setLayoutParams(lp);
        img.setScaleType(ScaleType.CENTER_CROP);
    }

    /** 為 ImageView 設定圖片 */
    private void setImageBitmap(ImageView img, String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            img.setImageBitmap(BitmapFactory.decodeStream(fis));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /** 圖片物件 */
    class ImageBean {
        private String path;
        public String getPath() { return path; }
        public void setPath(String path) { this.path = path; }
    }
}

兩個學習重點

一、換行是靠取模運算。updateLayout() 的核心就這一行:

if (i % 4 == 0) {
    ll_horizontal = new LinearLayout(context);
    ll_horizontal.setOrientation(LinearLayout.HORIZONTAL);
    linearLayout.addView(ll_horizontal);
}

每遇到 4 的倍數就新建一個橫向容器,其後的圖片都掛到這個容器上,直到下一個 4 的倍數出現。要改每行數量,改這個 4 就好。

注意開頭要先 removeAllViews(),否則每次呼叫都會在舊內容上追加,圖片會愈疊愈多。

二、尺寸計算要扣掉邊距。那串看似複雜的算式在解決一個實際問題:螢幕寬度扣掉左右內距、再扣掉四個圖片之間的三道間距,剩下的除以 4 才是單張圖的寬度。

lp.width = (int) ((螢幕寬 - 左右內距 - 間距總寬) / 4);

把高度設成與寬度相同即可得到正方形格子,再搭配 ScaleType.CENTER_CROP,圖片會填滿格子並均勻裁切,不會變形。

幾個可以改進的地方

managedQuery 已過時。它會讓 Activity 代管 Cursor 生命週期,在舊版本上方便,但現在不建議使用。改而自己管理 Cursor 並在 onDestroy 中 close(),或直接用 ContentResolver.query()。

每次都全量重建效能不佳。updateLayout() 每次都 removeAllViews() 再全部重建,圖片多時會明顯卡頓。改良方式是只新增那一筆,或者改用 RecyclerView + GridLayoutManager——這其實就是最初想用的 GridView 現代版,換行、間距、視圖復用全部由 LayoutManager 代勞,不必手算。

decodeStream 有 OOM 風險。原圖直接解碼成 Bitmap,幾張就會記憶體不足。應該用 inSampleSize 先取樣縮小。

這個手寫做法的價值在於把「換行」這件事的原理攤開來看——一旦理解了巢狀容器與取模分配,就會明白 GridLayoutManager 背後做的是同一件事,只是它還額外幫你處理了復用與滾動。

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