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

Android 電商實戰(二):仿淘寶商品屬性標籤頁的自動換行實現

編輯:關於 Android 程式設計

先看效果

需求:屬性與標籤都不能寫死

電商商品詳情頁裡的「規格選擇」看起來簡單,實際上有兩個層次的不確定性:

屬性本身是不確定的。有的商品是「顏色 + 尺碼」,有的是「口味」,有的是「容量」。這些屬性名稱與數量都由後端下发,不可能在頁面裡預先寫死。

每個屬性下的標籤數量同樣不確定。尺碼可能是 S / M / XL,也可能只有一個「均碼」;顏色可能有十幾種。標籤個數與文字長度都無法預知。

因此,頁面必須做到:屬性列表動態生成,且每個屬性下的標籤能依內容長短自動換行。

技術點:自定義可換行的 ViewGroup

標準的 LinearLayout 只能排成一行(或一欄),當一行放不下時不會自動換行。要實現標籤流式排列,就得自己寫一個容器。

實現思路

整體結構是:外層用 ListView 展示所有屬性,每個屬性作為一個 Item;Item 內部放一個自定義的 MyViewGroup,標籤以 TextView 的形式動態 addView 進去。

自定義 ViewGroup 的關鍵:onMeasure 與 onLayout

onMeasure 負責算出「需要幾行、總高度多少」;onLayout 負責把每個子 View 擺到正確位置,判斷依據是「加上這個子 View 後是否超出容器寬度」。

package jczb.shoping.common;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/** 子 View 可依內容自動換行的容器 */
public class MyViewGroup extends ViewGroup {

    private final static int VIEW_MARGIN = 15;
    private int jiange = 10; // 按鈕之間的間隔

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewGroup(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int stages = 1;      // 總共佔了幾行
        int stageHeight = 0; // 單行高度
        int stageWidth = 0;  // 當前行已用寬度
        int wholeWidth = MeasureSpec.getSize(widthMeasureSpec);

        for (int i = 0; i < getChildCount(); i++) {
            final View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);

            stageWidth += (child.getMeasuredWidth() + VIEW_MARGIN);
            stageHeight = child.getMeasuredHeight();

            // 當前行放不下,換行
            if (stageWidth >= wholeWidth) {
                stages++;
                stageWidth = child.getMeasuredWidth();
            }
        }

        int wholeHeight = (stageHeight + VIEW_MARGIN) * stages;

        setMeasuredDimension(
                resolveSize(wholeWidth, widthMeasureSpec),
                resolveSize(wholeHeight, heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int count = getChildCount();
        int row = 0;          // 相對於父容器的行號
        int lengthX = left;   // 子 View 相對於父容器的右邊界
        int lengthY = top;    // 子 View 相對於父容器的下邊界

        for (int i = 0; i < count; i++) {
            final View child = this.getChildAt(i);
            int width = child.getMeasuredWidth();
            int height = child.getMeasuredHeight();

            if (i == 0) {
                lengthX += width + VIEW_MARGIN; // 第一個不需要加間隔
            } else {
                lengthX += width + jiange;      // 加上按鈕間隔
            }

            lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + top;

            // 這一行放不下了,換到下一行
            if (lengthX > right) {
                lengthX = width + VIEW_MARGIN + left;
                row++;
                lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + top;
            }

            child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
        }
    }
}

ListView 的 Adapter

Adapter 做三件事:把屬性名稱綁到標題 TextView;依標籤陣列動態建立 TextView 並加入 MyViewGroup;為每個標籤綁定點選事件,並把使用者選擇結果存進 Map。

這裡有個實作細節值得注意:getView 中的動態添加必須加上 getChildCount() == 0 的判斷,否則 ListView 滾動時 convertView 被複用,標籤會不斷重複堆疊。

package jczb.shoping.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import jczb.shoping.common.MyViewGroup;
import jczb.shoping.ui.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PropertyAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<HashMap<String, Object>> mList;
    private Handler mHandler;
    private Drawable drawableNormal;
    private Drawable drawablePressed;

    /** 用於保存使用者的屬性選擇結果 */
    private HashMap<String, String> selectProMap = new HashMap<String, String>();

    public HashMap<String, String> getSelectProMap() {
        return selectProMap;
    }

    public void setSelectProMap(HashMap<String, String> selectProMap) {
        this.selectProMap = selectProMap;
    }

    public PropertyAdapter(Handler handler, Context context,
                           ArrayList<HashMap<String, Object>> list) {
        this.mHandler = handler;
        this.mContext = context;
        this.mList = list;
        drawableNormal = mContext.getResources().getDrawable(R.drawable.tv_property_label);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = LayoutInflater.from(this.mContext)
                    .inflate(R.layout.lv_property_item, null, true);
            holder = new ViewHolder();
            holder.tvPropName = (TextView) convertView.findViewById(R.id.tv_property_name);
            holder.vgPropContents = (MyViewGroup) convertView.findViewById(R.id.myviewgroup);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (this.mList == null) {
            return convertView;
        }

        ArrayList<String> lables =
                (ArrayList<String>) this.mList.get(position).get("lable");
        String type = (String) this.mList.get(position).get("type");
        holder.tvPropName.setText(type); // 規格名稱

        // 判斷子控件是否為 0,不為 0 則不再添加,避免 ListView 滾動時重複添加
        if (holder.vgPropContents.getChildCount() == 0) {
            TextView[] textViews = new TextView[lables.size()];

            for (int i = 0; i < lables.size(); i++) {
                TextView textView = new TextView(mContext);
                textView.setGravity(17);
                textView.setPadding(25, 15, 25, 15);
                textView.setBackgroundResource(R.drawable.tv_property_label);
                textView.setText(lables.get(i));
                textView.setTag(i);
                textViews[i] = textView;
                holder.vgPropContents.addView(textViews[i]);
            }

            // 綁定標籤點擊事件
            for (int j = 0; j < textViews.length; j++) {
                final int index = j;
                textViews[j].setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView tv = (TextView) v;
                        selectProMap.put(type, (String) tv.getText());
                        // 更新選中態背景
                        for (int h = 0; h < holder.vgPropContents.getChildCount(); h++) {
                            TextView child =
                                    (TextView) holder.vgPropContents.getChildAt(h);
                            child.setBackgroundResource(R.drawable.tv_property_label);
                        }
                        tv.setBackgroundResource(R.drawable.tv_property_label_pressed);
                    }
                });
            }
        }

        return convertView;
    }

    class ViewHolder {
        TextView tvPropName;
        MyViewGroup vgPropContents;
    }
}

總結

整個方案的關鍵就在自定義 ViewGroup:重寫 onMeasure 算出總行數與高度,重寫 onLayout 依「是否超出容器寬度」決定要不要換行。屬性的動態加載則交給 ListView 的 Adapter,兩者組合起來,就能應對後端下发的任意屬性結構。此外別忘了 convertView 複用帶來的副作用——動態添加子 View 時一定要先判斷是否已添加過。

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