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

Android 動態生成九宮格版面,實作多圖片上傳

編輯:關於 Android 程式設計

動態版面 + 多圖上傳,一次搞定

本文示範如何在 Android 中不寫死 XML,而是用程式碼動態排出九宮格、補上分隔線與「+」號,再搭配非同步任務把多張圖片一次上傳。

先看在專案裡跑出來的樣子:

技術重點

1. 動態產生格線與每格的「+」號佔位圖示

2. 多張圖片非同步上傳

一、版面檔

父層乾淨得很,只有一個 LinearLayout 當容器,其餘全靠程式碼塞進去。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f2f2f2"
    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout
        android:id="@+id/layout_CONTAINER"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f2f2f2"
        android:orientation="vertical"
        android:padding="5dp">
    </LinearLayout>

</LinearLayout>

橫線與縱線的版面也各自獨立成 layout_line_horizonal.xml 與 layout_line_vertical.xml,需要時 inflate 進來即可,好處是線條樣式要改不必動主程式。

二、動態組裝九宮格

思路是「三個一組」:外層跑列,內層跑欄,每遇到非第一列或第一欄就補一條線,格子本身則用權重 1 平均分配寬度。

private void initUI() {
    setContentView(R.layout.activity_main);
    mLayout = (ViewGroup) findViewById(R.id.layout_container);

    final int count = 9;                    // 總共九格
    final int rowCount = (count + 2) / 3;   // 三欄,向上取整算列數

    for (int i = 0; i < rowCount; i++) {
        if (i != 0) {
            // 非第一列,先補橫線
            View.inflate(this, R.layout.layout_line_horizonal, mLayout);
        }

        final LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setBackgroundResource(R.drawable.row_selector);

        for (int j = 0; j < 3; j++) {
            if (j != 0) {
                // 非第一欄,補縱線
                View.inflate(this, R.layout.layout_line_vertical, linearLayout);
            }

            ImageButton imageButton = new ImageButton(this);
            imageButton.setBackgroundResource(R.drawable.row_selector);
            imageButton.setTag(TAG);
            imageButton.setOnClickListener(this);
            imageButton.setEnabled(false);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
            linearLayout.addView(imageButton, lp);
            mImageButtonList.add(imageButton);
        }

        DisplayManager manager = DisplayManager.getInstance();
        LayoutParams lp = new LayoutParams(
                LayoutParams.MATCH_PARENT, manager.dipToPixel(100));
        mLayout.addView(linearLayout, lp);
    }

    // 只有當前這一格顯示「+」並開放點擊
    final ImageButton currentImageButton = mImageButtonList.get(mCurrent);
    currentImageButton.setImageResource(R.drawable.ic_add_picture);
    currentImageButton.setScaleType(ScaleType.CENTER);
    currentImageButton.setEnabled(true);
}

三、非同步上傳

用 AsyncTask 在背景執行緒逐一處理圖片檔,並透過 publishProgress() 回報進度;上傳成功的網址往 mPictureUrlList 塞,之後要回填伺服器就直接取這個清單。

private class UploadPictureTask extends AsyncTask<List<String>, Integer, String> {

    @Override
    protected String doInBackground(List<String>... params) {
        final List<String> pictureList = params[0];
        for (int i = 0, len = pictureList.size(); i < len; i++) {
            final File file = new File(pictureList.get(i));
            // 這裡接上你的上傳實作
            // final String response = ApacheHttpUtils.post(mUrlPrefix + "/upload", new File[]{file});
            // final UploadInfo upload = new UploadParser().parse(response).getData();
            // if (upload != null && upload.getUrl() != null) {
            //     mPictureUrlList.add(upload.getUrl());
            // }
            publishProgress(i);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) { }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}

四、三個清單各司其職

類別裡宣告了三份清單,分別記錄「格子 View」「本地圖片路徑」「上傳後的遠端網址」,這樣整個流程的狀態都攤在明面上,除錯時一目了然。

mImageButtonList = new ArrayList<ImageButton>();
mPicturePathList = new ArrayList<String>();
mPictureUrlList  = new ArrayList<String>();

實作時要留意的細節:格子被點滿之後要記得把最後一格的「+」隱藏或改成送出按鈕;另外 AsyncTask 在清單被銷毀時記得取消,免得回呼打到已經關掉的 Activity。

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